SQL日期字段和唯一ID组合可生成运行月份

时间:2019-02-06 19:20:37

标签: sql sql-server tsql

需要使用日期和ID字段组合在sql中生成运行月份。 需要生成“月”列格式。

enter image description here

提前谢谢!

1 个答案:

答案 0 :(得分:0)

您在寻找这样的东西吗?

WITH cte
AS (   SELECT *, MONTH(Date) AS monthNum
       FROM tablename),
     cte2
AS (   SELECT *,
           FIRST_VALUE(cte.monthNum) OVER (PARTITION BY date
                                           ORDER BY ID) AS firstval,
           ROW_NUMBER() OVER (PARTITION BY ID ORDER BY id) AS ROWNUM
       FROM cte)
SELECT ID,
    DATE,
    (cte2.firstval + cte2.ROWNUM) - 1 AS 'Month'
FROM cte2;

上面的代码将提取Month并将相同ID的值加1。