我有下表:
ID | Name | Value1 | Value2
1 | A | 1000 | 2000
2 | A | 3000 | 4000
1 | C | 1100 | 2200
2 | B | 1500 | 2500
我想输出下表:
ID | Name | Value1 | Value2
1 | A | 1000 | 2000
2 | A | 3000 | 4000
1 | C | 1100 | 2200
2 | B | 1500 | 2500
2 | C | 1100 | 2200
1 | B | 1500 | 2500
所以基本上我想为每个Name复制每个ID的缺失值(ID只有两个值 - 1或2)。只有当我知道一个ID包含所有可用的名称时,我才可以在表本身上使用LEFT JOIN。有没有更好的办法?我正在使用SQL Server 2014。
提前致谢。
答案 0 :(得分:3)
SELECT A1.ID, A2.NAME, ISNULL(A.Value1, A3.Value1) Value1, ISNULL(A.Value2,
A3.Value2) Value2 FROM
(SELECT DISTINCT ID FROM MyTable) A1 CROSS APPLY
(SELECT DISTINCT NAME FROM MyTable) A2 OUTER APPLY
(SELECT TOP 1 Value1, Value2 FROM MyTable A3 WHERE A3.NAME = A2.NAME) A3
LEFT JOIN MyTable A ON A.ID = A1.ID AND A.NAME = A2.NAME
ORDER BY A1.ID, A2.NAME