Categories:
Cloud (204)
Entertainment (11)
Facebook (43)
General (50)
Life (31)
Programming (64)
Technology (398)
Testing (4)
Tools (488)
Twitter (5)
Wearable (26)
Web Design (44)
Collections:
Other Resources:
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?
✍: FYIcenter
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, 1709🔥, 1💬
Popular Posts:
How to add a new layout to the slide master in PowerPoint? In my PowerPoint presentation, I need to ...
How to add a new layout to the slide master in PowerPoint? In my PowerPoint presentation, I need to ...
How to unzip a Word Document .docx file? According to Microsoft documentation, a .docx file is reall...
How register my Fitbit device through Fitbit Connect? I have an account with Fitbit server, installe...
How to download Google Chrome 31? I heard it has some really nice features for Web developers. If yo...