I have a MSSQL table stores that has the following columns in a table:
Storeid, NumEmployees
1 125
2 154
3 10
4 698
5 54
6 98
7 87
8 100
9 58
10 897
Can someone help me with the SQL query to produce the top stores(storeID) that has 30% of the total emplyees(NumEmployees)?
Working Demo
Alternative that doesn’t use SUM/OVER
Working Demo
Note that in the second version I decided not to multiply by 100 before dividing. This requires a cast to decimal otherwise it would be implicitly converted to a int resulting in no records returned
Also I’m not completely clear that you want this, but you can add
TOP 1to both queries and it will limit the results to just the one with the greatest # of stores with more than 30%UPDATE
Based on your comments it sounds to paraphrase Kevin
This is difficult because it requires a running percentage and its a bin packing problem however this does work. Note I’ve included two other test cases (where the percent exactly equals and its just over the top two combined)
Working Demo