我有一张类似
的表格Year Month ID Date Status
--------------------------------------
2013 8 99999 8/1/2013 Status A
2013 9 99999 NULL NULL
2013 10 99999 NULL NULL
2013 11 99999 NULL NULL
2013 12 99999 NULL NULL
2014 1 99999 NULL NULL
2014 2 99999 2/5/2014 Status B
2014 3 99999 NULL NULL
2014 4 99999 NULL NULL
2014 5 99999 NULL NULL
2014 6 99999 NULL NULL
2014 7 99999 NULL NULL
我想添加一个列,它会给出状态编号,重复到下一次出现状态,然后添加1。
结果:
Year Month ID Date Status Value
--------------------------------------------
2013 8 99999 8/1/2013 Status A 1
2013 9 99999 NULL NULL 1
2013 10 99999 NULL NULL 1
2013 11 99999 NULL NULL 1
2013 12 99999 NULL NULL 1
2014 1 99999 NULL NULL 1
2014 2 99999 2/5/2014 Status B 2
2014 3 99999 NULL NULL 2
2014 4 99999 NULL NULL 2
2014 5 99999 NULL NULL 2
2014 6 99999 NULL NULL 2
2014 7 99999 NULL NULL 2
Nulls是什么让我失望...感谢您的帮助!
编辑:
这是我当前的查询:
DECLARE @DateStart DATETIME
DECLARE @DateEnd DATETIME
SET @DateStart = '8/1/2013'
SET @DateEnd = '7/1/2014'
SELECT
P.Year, P.Month, P.ID,
PP.MaxStatusDate,
Status
FROM
(SELECT
*
FROM
(SELECT DISTINCT
year, Month
FROM
lu_Calendar
WHERE
Date BETWEEN @DateStart AND @DateEnd) AS A
CROSS JOIN
(SELECT DISTINCT
ID
FROM
dbo.StatusChangeData) AS B
) AS P
LEFT JOIN
(SELECT
yr, mnth, MaxStatusDate, Status, A.ID
FROM
(SELECT
ID, YEAR([ModifiedDate]) AS yr,
MONTH(ModifiedDate) AS mnth,
MAX([ModifiedDate]) AS MaxStatusDate
FROM
dbo.StatusChangeData
GROUP BY
ID, YEAR([ModifiedDate]), MONTH(ModifiedDate)) AS A
INNER JOIN
dbo.StatusChangeData sce ON sce.ID = A.ID AND A.MaxStatusDate = sce.[ModifiedDate]
) AS PP ON P.Month = pp.mnth AND P.YEAR = PP.yr AND P.ID = PP.ID
WHERE
P.ID = 99999
答案 0 :(得分:0)
您可以使用相关子查询执行此操作。从本质上讲,这会计算任何给定值之前的非NULL
值的数量:
select scd.*,
(select count(*)
from StatusChangeData scd2
where scd2.id = scd.id and
scd2.status is not null and
scd2.year*100+scd2.month <= scd.year*100+scd.month
) as value
from StatusChangeData scd;