使用SQL Server 2012:我有一个简单的表:
CREATE TABLE simpletable
(
[key] INT NOT NULL IDENTITY(1,1),
[id] INT,
[ca] INT,
[cp] INT,
[ct] INT
)
由于各种原因,这个表每[ca],[cp]和[ct]只有一行 - 就像这样:
INSERT INTO simpletable ([id], [ca], [cp], [ct])
VALUES (1, 10, null, null),
(1, null, 20, null),
(1, null, 120, null),
(1, null, null, 30),
(2, 11, null, null),
(2, null, 21, null),
(2, null, null, 31),
(2, null, null, 231)
我想要实现的(没有游标)是将所有组合分解为临时表或表类型变量;像这样的东西:
id ca cp ct
---------------
1 10 20 30
1 10 120 30
2 11 21 31
2 11 21 231
我非常感谢你的帮助。
答案 0 :(得分:2)
这是一种(繁琐)的方式:
SELECT dca.[id], dca.[ca], dcp.[cp], dct.[ct]
FROM
(
SELECT [id], [ca]
FROM simpletable
WHERE [ca] IS NOT NULL
) dca
INNER JOIN
(
SELECT [id], [cp]
FROM simpletable
WHERE [cp] IS NOT NULL
) dcp ON dca.id = dcp.id
INNER JOIN
(
SELECT [id], [ct]
FROM simpletable
WHERE [ct] IS NOT NULL
) dct ON dca.id = dct.id
注意此解决方案基于以下假设:除id
之外必须至少有一列不是每行都为空。