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, 1095👍, 1💬
How to add a picture to a PowerPoint slide? I have a very nice picture I took from a meeting. Can I ...
Where to find answers to frequently asked questions about Microsoft Office 365? Here is a collection...
How to install Mozilla Firefox 2.0 add-on: FireFTP? FireFTP is a Mozilla Firefox 2 add-on that provi...
What are URL:sfb and URL:lync15 Protocols? URL:sfb and URL:lync15 protocols are special network prot...
What is a slide master in PowerPoint? A slide master is a set of slide layouts defined to help you c...