选择按日期记录的最高发生次数

时间:2017-12-01 19:43:37

标签: sql sql-server tsql

表格结构:

ScheduledDate Date
Commodity varchar    

示例数据

ScheduledDate | Commodity
--------------+------------
 2017-11-27   | KIDNEY BEANS
 2017-11-27   | KIDNEY BEANS
 2017-11-27   | RED BEANS
 2017-11-28   | LARGE GREEN LENTIL
 2017-11-28   | SMALL GREEN LENTIL
 2017-11-29   | LARGE GREEN LENTIL

我需要的是:表格中每日最多的商品有一条记录,按日期排序。所以期望的输出是:

ScheduledDate | Commodity
--------------+------------
 2017-11-27   | KIDNEY BEANS
 2017-11-28   | LARGE GREEN LENTIL
 2017-11-29   | LARGE GREEN LENTIL

...如果多个商品在某个日期出现的次数相同,那么我只需要退回一次。没有真正的偏好。

我认为我非常接近,但只需要最后一块拼图来解决这个问题......

SELECT
     ScheduledDate
    ,Commodity
    ,OCCURANCE_COUNT = MAX(OCCURANCES)
FROM (
    SELECT 
        ScheduledDate
        ,Commodity
        ,OCCURANCES = COUNT(Commodity)
    FROM 
        vwScheduledLoads 
    GROUP BY
        ScheduledDate,
        Commodity
) qc
GROUP BY
    ScheduledDate
    ,Commodity
ORDER BY
    ScheduledDate

...内部SQL做了我想要的,我想要对结果进行分组的部分就是我难以接受的。该查询吐出以下内容:

ScheduledDate | Commodity          | OCCURANCE_COUNT
--------------+--------------------+-----------------
 2017-11-27   | KIDNEY BEANS       | 2
 2017-11-27   | RED BEANS          | 1
 2017-11-28   | LARGE GREEN LENTIL | 1
 2017-11-28   | SMALL GREEN LENTIL | 1
 2017-11-29   | LARGE GREEN LENTIL | 1

1 个答案:

答案 0 :(得分:5)

您希望使用row_number()汇总查询:

select ScheduledDate, Commodity
from (select ScheduledDate, Commodity, count(*) as cnt,
             row_number() over (partition by ScheduledDate order by count(*) desc) as seqnum
      from t
      group by ScheduledDate, Commodity
     ) sc
where seqnum = 1;