例如,有一些日期表:
2015-01-01 2015-01-02 2015-01-03 2015-01-06 2015-01-07 2015-01-11
我必须编写ms SQL查询,它将返回从表中每个日期开始的连续日期的计数.结果如下:
2015-01-01 1 2015-01-02 2 2015-01-03 3 2015-01-06 1 2015-01-07 2 2015-01-11 1
在我看来,我应该使用LAG和LEAD功能,但现在我甚至无法想象思维方式.
解决方法
CREATE TABLE #T ( MyDate DATE) ; INSERT #T VALUES ('2015-01-01'),('2015-01-02'),('2015-01-03'),('2015-01-06'),('2015-01-07'),('2015-01-11') SELECT RW=ROW_NUMBER() OVER( PARTITION BY GRP ORDER BY MyDate),MyDate FROM ( SELECT MyDate,DATEDIFF(Day,'1900-01-01',MyDate)- ROW_NUMBER() OVER( ORDER BY MyDate ) AS GRP FROM #T ) A DROP TABLE #T;