Categories:
Cloud (161)
Entertainment (11)
Facebook (43)
General (16)
Life (30)
Programming (33)
Technology (224)
Testing (4)
Tools (431)
Twitter (5)
Wearable (26)
Web Design (9)
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, 1213👍, 1💬
Popular Posts:
What are control codes used in Microsoft Word that can be used in the Find and Replace command? Here...
Why am I not seeing the "Call Forwarding" option on Skype for Business on Windows? You don't see the...
What is TestReail? TestRail is a comprehensive web-based test case management software to efficientl...
Where to find answers to frequently asked questions about Microsoft Office 365? Here is a collection...
How to use MomoCast with Safari on iPhone and iPad to cast Website and video to Chromecast on TV? If...