I am trying to get a return that gives me the top 80% of the values returned. Using SQL DB for i the TOP clause will not work. I have seen some examples of using Count() in a nested select statement, but I am not sure how that is supposed to fit into the query I have already written. I already have 2 sub-query’s so I need to find out how it would fit, or if it would work. Here is what I have so far:
Select CATEGORY,
LINE,
ITEM#,
Units
From D*****.*****ST
Inner Join (Select DW******.*****FO.ITEM,
Sum (SALES_UNITS) As Units,
CATEGORY
From DW*******.*****FO
Inner Join (Select CATEGORY,
DW****.******RY.ITEM
From DW****.******RY
Where CATEGORY='BRAKES') As CA***ST
On DW*******.*****FO.ITEM=CA*****.***M
Where ("DATE" between current date -1 years and current date) And (SALES > 5.00)
Group By DW*******.******O.ITEM,
CATEGORY) As Units_List
On DW****.*****ST.**EM#=U*********.***M
Group By CATEGORY,
LINE,
ITEM#,
Units
Order By Units DESC
So somewhere in here would be the nested Count() clause I’m assuming, I’m just not sure where it fits in the grand scheme of things. I’m still learning some of the intermediate SQL stuff, so I’m sorry if the question seems a little simple.
I would suggest using window functions. I find your query hard to follow, but here is the idea:
The idea is to use window functions to get the total count and also the ranking (I use
row_number(),rank()might be more appropriate if you have ties). You can then just use awhereclause to get the values you want.