SQL每年选择前10名

时间:2016-05-11 22:22:08

标签: sql-server

我有一个事实数据库,我希望根据每个项目每年的总金额,根据前10个项目制作趋势线。 我已经完成了以下工作,但它确实为我的2007年选择了10多个实体:

select TOP 10 sum(Quantity) as Quantity,DIM_Time.Year, DIM_Item.Name as Name 

from Fact_Purchase
join DIM_Item on DIM_Item.BKey_ItemId = Fact_Purchase.DIM_Item
join DIM_Time on DIM_Time.ID = Fact_Purchase.DIM_Time_DeliveryDate
where Fact_Purchase.DIM_Company = 2 and DIM_Time.ID = FACT_Purchase.DIM_Time_DeliveryDate

Group by dim_item.Name, DIM_Time.Year
Order by Quantity DESC 

如何在我的所有年份中选择数量最多的前10个项目,每年只有10个顶级实体?

你可以猜到,公司是个人的,并且将成为我报告中的一个参数

2 个答案:

答案 0 :(得分:2)

我认为这就是你的目标。如果我搞砸你的桌子,我很抱歉。

select *
from (
    select DIM_Time.[Year], dim_item.Name, SUM(Quantity) Quantity, RANK() OVER (PARTITION BY DIM_Time.[Year] ORDER BY SUM(Quantity) DESC) salesrank
    from Fact_Purchase
        join DIM_Item on DIM_Item.BKey_ItemId = Fact_Purchase.DIM_Item
        join DIM_Time on DIM_Time.ID = Fact_Purchase.DIM_Time_DeliveryDate
    where Fact_Purchase.DIM_Company = 2 and DIM_Time.ID = FACT_Purchase.DIM_Time_DeliveryDate
    group by dim_item.Name, DIM_Time.[Year]
) tbl
where salesrank <= 10
order by [Year], salesrank

子查询按名称/年分组,RANK()OVER部分设置一种行索引,按SUM(数量)递增,并为每年重新启动。从那里你只需要过滤掉任何超过10的salesrank(索引)。

答案 1 :(得分:0)

SELECT 
    _year,
    Name,
    _SUM,
    RANK_iD
    FROM 
        (
            SELECT 
                _year,
                Name,
                _SUM,
                DENSE_RANK()OVER(PARTITION BY _year,_Month ORDER BY _SUM DESC) AS RANK_iD
            FROM(
                Select 
                    DIM_Time AS _year,
                    DIM_Item as Name,
                    sum(Quantity) AS _SUM
                from 
                    #ABC
                GROUP BY 
                    _year,
                    Name
             )A
         )B
    WHERE RANK_iD<=10