每月,每年SQL Server 2008选择十大销售额

时间:2014-05-30 08:23:56

标签: sql-server-2008

SELECT tr.createdon, 
       st.be_storecountry, 
       st.be_storelocationcategory,
       st.be_name as storename, 
       br.be_name as brand, 
       SUM(sd.be_amount) as total
from 
       Filteredbe_transaction tr, 
       Filteredbe_store st,
       Filteredbe_salesdetails sd, 
       Filteredbe_brand br
Where
       sd.be_itembrand = br.be_brandid and
       tr.be_storename = st.be_storeid and
       tr.be_transactionid = sd.be_transactionid and
       tr.createdon between '1/1/2008' and '1/1/2014'
group by 
       tr.createdon, st.be_storecountry, st.be_storelocationcategory,
       st.be_name, br.be_name
Order by 
       tr.createdon desc

这是我的查询,它返回286行。我需要对其进行修改,以便每年从每个月获得前十名的销售额。因此,从2008年到2014年的每年的每个月必须只有10个相应的结果,那些必须是最大销售额。任何人都可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

您可以使用partition根据月份和年份将其分解为子集,然后从结果中选择每个此类子集的前10位,如下所示:

;with cte as
(
 SELECT tr.createdon, 
   st.be_storecountry, 
   st.be_storelocationcategory,
   st.be_name as storename, 
   br.be_name as brand, 
   SUM(sd.be_amount) as total
from 
   Filteredbe_transaction tr, 
   Filteredbe_store st,
   Filteredbe_salesdetails sd, 
   Filteredbe_brand br
Where
   sd.be_itembrand = br.be_brandid and
   tr.be_storename = st.be_storeid and
   tr.be_transactionid = sd.be_transactionid and
   tr.createdon between '1/1/2008' and '1/1/2014'
group by 
   tr.createdon, st.be_storecountry, st.be_storelocationcategory,
   st.be_name, br.be_name
),
filtered as
(
 select *, 
 row_number() over (partition by year(createdon),month(createdon) order by total desc) rn
from cte)

select * from filtered
where rn <= 10