我有下表:
Query ID No_ Name Value Description
3 PP120 C1 0 NULL
2 PP121 NULL 140 Positive
3 PP122 C1 0 NULL
3 PP123 C1 0 NULL
3 PP124 C1 0 NULL
3 PP125 C1 0 NULL
2 PP126 NULL 170 Positive
2 PP127 NULL -658 Positive
2 PP128 NULL 547 Positive
3 PP129 C1 0 NULL
3 PP130 C1 0 NULL
3 PP131 C1 0 NULL
这是两个不同查询结合的结果(参见ID查询):
SELECT [Query ID]=2, SL.[No_], CL.[Name] ,SL.Value, SL.Type
FROM SLine SL
LEFT JOIN CLine CL ON SL.[No_] = CL.[No_]
WHERE
SL.[Type] <> ''
UNION
SELECT [Query ID]=3, SL.[No_], CL.[Name] ,SL.Value, SL.Type
FROM SLine] SL
LEFT JOIN CLine CL ON SL.[No_] = CL.[No_]
WHERE
SL.[Type] <> ''
我需要将所有变量'name'替换为在不同的Query ID上具有相同No_的值。即我需要:
Query ID No_ Name Value Description
3 PP120 C1 0 NULL
2 PP121 C1 140 Positive
3 PP122 C1 0 NULL
3 PP123 C1 0 NULL
3 PP124 C1 0 NULL
3 PP125 C1 0 NULL
2 PP126 C1 170 Positive
2 PP127 C1 -658 Positive
2 PP128 C1 547 Positive
3 PP129 C1 0 NULL
3 PP130 C1 0 NULL
3 PP131 C1 0 NULL
我提供给你的表格只是结果的12000行的一部分。我尝试以下内容为每个No_获取相同的名称,但由于我需要使用SQL Server 2008,因此我无法使用以下代码:
SELECT
CASE WHEN [Name] IS NULL THEN LEAD([Name], 1, 0) OVER
(PARTITION BY [No_] ORDER BY [No_] ASC) AS [Name_], * FROM (
SELECT [Query ID]=3, SL.[No_], CL.[Name] ,SL.Value, SL.Type
FROM SLine SL
LEFT JOIN CLine CL ON SL.[No_] = CL.[No_]
WHERE
SL.[Type] <> ''
UNION
SELECT [Query ID]=2, SL.[No_], CL.[Name] ,SL.Value, SL.Type
FROM SLine] SL
LEFT JOIN CLine CL ON SL.[No_] = CL.[No_]
WHERE
SL.[Type] <> ''
)V
有任何建议可以替代LAG功能吗?
答案 0 :(得分:3)
使用CTE和row_number,然后自联接创建伪滞后/导致
With CTE as
(
select Q1.*, row_number() over (order by [No_]) rn
from MyQuery Q1
)
select C1.*,
case when c2.Column is null then C1.Column else c2.Column end as Pseudo_Lead
from CTE c1
left join CTE c2
on c2.rn = c1.rn +1
and <any other partition conditions>