按日期排名前5位的销售额

时间:2019-05-17 10:21:12

标签: sql

您好,您想知道如何获得前5名销售额的排名。

我有下表:

date          product      value
31/01/2018    calca        100
31/01/2018    calca        50
31/01/2018    camisa       30
31/01/2018    camisa       30
31/01/2018    sapato       75
31/01/2018    bermuda      100
31/01/2018    meia         10
31/01/2018    tenis        65
31/01/2018    luva         20
31/01/2018    luva         20
31/01/2019    calca        100
31/01/2019    calca        50
31/01/2019    camisa       30
31/01/2019    camisa       30
31/01/2019    sapato       75
31/01/2019    bermuda      100
31/01/2019    meia         10
31/01/2019    tenis        65
31/01/2019    luva         20
31/01/2019    luva         20 

预期结果按日期显示的总销售量为5。

date          prodct       value   rank
31/01/2018    calca        150       1
31/01/2018    bermuda      100       2
31/01/2018    sapato       75        3
31/01/2018    tenis        65        4
31/01/2018    camisa       60        5
31/01/2019    calca        150       1
31/01/2019    bermuda      100       2
31/01/2019    sapato       75        3
31/01/2019    tenis        65        4
31/01/2019    camisa       60        5

如果有人有一个简单的解决方案,谢谢。

4 个答案:

答案 0 :(得分:1)

您可以使用row_number()dense_rank()(如果您与价值有联系):

select t.*
from (select date, product, sum(value) as value,
             dense_rank() over (partition by date order by sum(value) desc) as rank
      from table t
      group by date, product
     ) t
where rank <= 5;

答案 1 :(得分:1)

Dim lst = (From t In context.MasterTable.Where(Function(t1) t1.id = 7) Select New With { t, .chld1 = t.child1s.Where(Function(t21) t21.vl1 >5), .chld2 = t.child2s.Where(Function(t31) t31.vl2>6 ), .chld3 = (From t2 in t.child3s.Where(Function(t41) t41.vl3>7) Select New With { t2, .chld3it=t2.Child3Itms }) }).ToList 中,您通常会这样:

SQL

是您要找的东西吗?

答案 2 :(得分:1)

您需要具有窗口功能的聚合。像这样:

select date, product, value
from (select date, product, sum(value) as value,
             row_number() over (partition by date order by sum(value) desc) as seqnum
      from t
      group by date, product
     ) t
where seqnum <= 5
order by date, value desc;

答案 3 :(得分:0)

尝试

SELECT TOP (5) date ,product 
      ,value
      ,rank () over (order by value desc) rank_order
  FROM TableA