我在MSSQL表中有一些如下所示的数据:
price, date
15.98, 2014-05-31 13:24:05.287
15.98, 2014-06-01 01:24:15.250
15.98, 2014-06-01 13:24:19.280
15.98, 2014-06-02 01:25:01.680
15.98, 2014-06-02 13:25:10.477
9.99, 2014-06-03 01:25:12.580
15.98 2014-06-03 13:26:01.930
15.98 2014-06-04 01:26:11.423
9.99 2014-06-04 13:26:17.853
9.99 2014-06-05 01:27:01.800
我想返回每个价格的数量,但不是将所有价格分组在一起,我想根据时间进行分组。我想回来的结果是:
price, count
15.98, 5
9.99, 1
15.98, 2
9.99, 2
我如何操作GROUP BY子句来产生上面的集合?
答案 0 :(得分:1)
这(连续范围的分组)被称为间隙和岛屿问题,可以通过使用分析函数(特别是ROW_NUMBER()
)来有效地解决
SELECT price, COUNT(*) count
FROM
(
SELECT price, date,
ROW_NUMBER() OVER (ORDER BY date) rnum,
ROW_NUMBER() OVER (PARTITION BY price ORDER BY date) rnum2
FROM table1
) q
GROUP BY price, rnum - rnum2
ORDER BY MIN(rnum)
输出:
| PRICE | COUNT | |-------|-------| | 15.98 | 5 | | 9.99 | 1 | | 15.98 | 2 | | 9.99 | 2 |
这是 SQLFiddle 演示