Row_num和DATE分区?

时间:2015-11-30 10:49:50

标签: sql sql-server date sql-server-2012 window-functions

我很难找到row_number partition by的解决方案。

我的表看起来像这样(*这是我唯一的列*)

enter image description here

我的脚本是这样的:

SELECT 
    [P_ID],
    [DATE],
    ROW_NUMBER() OVER (PARTITION BY P_ID,[DATE] ORDER BY P_ID,[DATE] ) AS ROW
FROM #TEMP

我希望按DATE分组,第一行应该说1,第二行也应该说1,但第三行应该说2,因为日期是(顺序)15然后是16,如果有17则该行会说3但是如果有一个新的行说2015-09-21那么它会回到第1行等等......

这可以通过分区吗?

1 个答案:

答案 0 :(得分:1)

以下是使用孤岛和间隙解决方案的解决方案:

DECLARE @t TABLE ( id INT, date DATE )
INSERT  INTO @t
VALUES  ( 2143, '20150902' ),
        ( 2143, '20150915' ),
        ( 2143, '20150916' ),
        ( 2143, '20150917' ),
        ( 2144, '20150902' ),
        ( 2144, '20150903' ),
        ( 2144, '20150916' ),
        ( 2144, '20150917' );

WITH    cte1
          AS ( SELECT   id ,
                        date ,
                        ROW_NUMBER() OVER ( PARTITION BY id ORDER BY date ) i
               FROM     @t
               GROUP BY id ,
                        date
             ),
        cte2
          AS ( SELECT   id ,
                        MIN(date) mi ,
                        MAX(date) ma ,
                        ROW_NUMBER() OVER ( ORDER BY ( SELECT NULL
                                                     ) ) rn
               FROM     cte1
               GROUP BY id ,
                        DATEDIFF(DAY, i, date)
             )
    SELECT  t.* ,
            ROW_NUMBER() OVER ( PARTITION BY t.id, c.rn ORDER BY date )
    FROM    @t t
            JOIN cte2 c ON t.id = c.id
                           AND t.date BETWEEN c.mi AND c.ma

输出:

2143    2015-09-02  1
2143    2015-09-15  1
2143    2015-09-16  2
2143    2015-09-17  3
2144    2015-09-02  1
2144    2015-09-03  2
2144    2015-09-16  1
2144    2015-09-17  2