根据列值添加列
add column based on a column value
我有这个table:
PersonID DateKey C/L
1 20140903 8
1 20140904 null
1 20140906 10
1 20140908 null
2 20140903 18
2 20140904 null
2 20140906 30
2 20140908 null
我需要添加另一列并重复 [C/L]
的值,结果 table 应如下所示:
PersonID DateKey C/L C/L_New
1 20140903 8 8
1 20140904 null 8
1 20140906 10 10
1 20140908 null 10
2 20140903 18 18
2 20140904 null 18
2 20140906 30 30
2 20140908 null 30
如果当前行的值为 NULL
,我想您需要上一行的值。
从 SQL Server 2012 您可以使用 LAG 功能:
SELECT PersonID
,DateKey
,[C/L]
,COALESCE([C/L], LAG([C/L], 1, NULL) OVER (ORDER BY PersonID, DateKey)) AS [C/L_New]
FROM YourTable
我猜你想要这个(假设 DateKey
是日期或日期时间列):
SELECT PersonID,
DateKey,
[C/L],
[C/L_New] = ISNULL([C/L], (SELECT TOP 1 t2.[C/L]
FROM dbo.TableName t2
WHERE t2.PersonID = t.PersonID
AND t2.DateKey <= t.DateKey
AND t2.[C/L] IS NOT NULL
ORDER BY DateKey DESC))
FROM dbo.TableName t
Order By PersonID, DateKey
编辑:DEMO
我有这个table:
PersonID DateKey C/L
1 20140903 8
1 20140904 null
1 20140906 10
1 20140908 null
2 20140903 18
2 20140904 null
2 20140906 30
2 20140908 null
我需要添加另一列并重复 [C/L]
的值,结果 table 应如下所示:
PersonID DateKey C/L C/L_New
1 20140903 8 8
1 20140904 null 8
1 20140906 10 10
1 20140908 null 10
2 20140903 18 18
2 20140904 null 18
2 20140906 30 30
2 20140908 null 30
如果当前行的值为 NULL
,我想您需要上一行的值。
从 SQL Server 2012 您可以使用 LAG 功能:
SELECT PersonID
,DateKey
,[C/L]
,COALESCE([C/L], LAG([C/L], 1, NULL) OVER (ORDER BY PersonID, DateKey)) AS [C/L_New]
FROM YourTable
我猜你想要这个(假设 DateKey
是日期或日期时间列):
SELECT PersonID,
DateKey,
[C/L],
[C/L_New] = ISNULL([C/L], (SELECT TOP 1 t2.[C/L]
FROM dbo.TableName t2
WHERE t2.PersonID = t.PersonID
AND t2.DateKey <= t.DateKey
AND t2.[C/L] IS NOT NULL
ORDER BY DateKey DESC))
FROM dbo.TableName t
Order By PersonID, DateKey
编辑:DEMO