SQL - 选择按多个字段分组的前n个,按计数排序

时间:2017-12-04 10:53:04

标签: sqlite greatest-n-per-group limit-per-group

我试图在按多个属性分组时找到前n个记录。我认为这与this problem有关,但我很难根据自己的情况调整所描述的解决方案。

为了简化,我有一个包含列的表(确实是device_id的缩写):

id int
did int
dateVal dateTime

我正在尝试找到排名最多的每一天的前n个device_id。

例如(忽略id和dateTime的时间部分),

did dateVal
1   2017-01-01
1   2017-01-01
1   2017-01-01
2   2017-01-01
3   2017-01-01
3   2017-01-01

1   2017-01-02
1   2017-01-02
2   2017-01-02
2   2017-01-02
2   2017-01-02
3   2017-01-02

找到前2名会产生......

1, 2017-01-01
3, 2017-01-01
2, 2017-01-02
1, 2017-01-02

我目前的天真态度只能让我在所有日期中排名前2位。

--Using SQLite
select date(dateVal) || did 
from data 
group by date(dateVal), did
order by count(*) desc 
limit 2

我使用连接运算符,以便以后可以提取行。

我正在使用SQLite,但任何一般的SQL解释都会受到赞赏。

2 个答案:

答案 0 :(得分:3)

this question类似,定义一个CTE,用于计算所需组的所有设备数,然后在WHERE ... IN子查询中使用它,仅限于该日期的前2个设备:

WITH device_counts AS (
  SELECT did, date(dateval) AS dateval, COUNT(*) AS device_count
  FROM data
  GROUP BY did, date(dateval)
)
SELECT did, date(dateval) FROM device_counts DC_outer
WHERE did IN (
  SELECT did
  FROM device_counts DC_inner
  WHERE DC_inner.dateval = DC_outer.dateval
  GROUP BY did, date(dateval)
  ORDER BY DC_inner.device_count DESC LIMIT 2
)
ORDER BY date(dateval), did

答案 1 :(得分:-1)

我使用sql server

测试了查询
select top 2 did, dateVal
from (select *, count(*) as c
      from test
      group by did,dateVal) as t
order by t.c desc