SQL Server Query with Percentage of Two Aggregated Values
How to write a single query to perform search based on a percentage criteria of two aggregated values?
For example, I have multiple pools of registration numbers in SQL Server database. Each registration number has a status of "Available" or "Registered". And I want to write a single query to find all pools that has less 20% available registration numbers?
One option to write a single query to perform on percentage of two aggregated values is to use inline views and apply the percentage criteria on the outer view.
if we have the following tables for your registration number example:
POOL table holds the list of pools with pool_id and name columns.
CODE table holds the list of registration numbers for each pool with pool_id, status, and value columns.
The search query to find all pools that has less 20% available registration numbers would be:
SELECT tt.* FROM (SELECT t1.pool_id, t1.name, t1.total, t2.available, CASE WHEN total=0 THEN 100 ELSE 100*available/total END ratio FROM (SELECT p.pool_id, p.name, COUNT(*) total FROM pool p, code c WHERE p.pool_id = c.pool_id GROUP BY p.pool, p.name ) t1, (SELECT p.pool_id, COUNT(*) available FROM pool p, code c WHERE p.pool_id = c.pool_id GROUP BY p.pool AND c.status='available' ) t2 WHERE t1.pool_id = t2.pool_id ) tt WHERE tt.ratio <= 20
In the query, "t1" view represents list of pools with total registration numbers in each pool. "t2" view represents list of pools with total available registration numbers in each pool. "tt" view combines "t1" and "t2" to represent a list of pools with total and available registration numbers, plus the percentage ratio of the two.
2016-06-12, 744👍, 1💬
Where to find answers to frequently asked questions on Google Chrome? I want to know how to install ...
Useful PHP Code Snippets for Developers - The Real Way To Check Uploaded File Type <?php // H...
How to edit Mozilla Firefox configuration file? Mozilla Firefox has a configuration file that contro...
How to install my DSL modem? I need to connect it with my phone and my wireless router. The diagram ...
How to Login to Microsoft Teams desktop version on my Windows 7 system? If you have Microsoft Teams ...