我有下表:
D1 D2 D3 D4 Proc_DtTm
716.90 NULL NULL NULL 2015-09-01 11:16:32.000
716.90 NULL NULL NULL 2015-09-01 13:59:26.000
716.90 NULL NULL NULL 2015-09-01 14:53:42.000
716.90 263.9 NULL NULL 2015-09-16 10:47:40.000
716.90 263.9 NULL NULL 2015-09-16 10:51:34.000
716.90 NULL NULL NULL 2015-09-16 10:54:42.000
716.90 NULL NULL NULL 2015-09-16 10:55:56.000
716.90 573.3 263.9 NULL 2015-09-16 10:56:09.000
716.90 573.3 263.9 NULL 2015-09-16 10:56:40.000
我的要求是:
示例:上表应返回字符串' 716.90,263.9,573.3'。
为了解决这个问题,我目前有一个非常复杂的函数,它使用游标循环遍历每个记录并将一些东西写入临时变量。我急于寻求解决方案,直到我能够重新审视并使其高效。任何人都可以提供一些关于如何在不使用基于光标的解决方案的情况下获得所需返回值的建议吗?
答案 0 :(得分:1)
你可以使用这种结构,但它看起来很丑陋。
WITH firstD1 AS (
SELECT TOP 1 D1 FROM yourTable WHERE D1 IS NOT NULL ORDER BY Proc_DtTm
),
other AS (
(
SELECT DISTINCT D1 FROM yourTable WHERE D1 IS NOT NULL
UNION
SELECT DISTINCT D2 FROM yourTable WHERE D2 IS NOT NULL
UNION
SELECT DISTINCT D3 FROM yourTable WHERE D3 IS NOT NULL
UNION
SELECT DISTINCT D4 FROM yourTable WHERE D4 IS NOT NULL
)
EXCEPT
SELECT D1 FROM firstD1
)
select (select DISTINCT STUFF((SELECT ',' + CAST(D1 as varchar(100))
FROM firstD1
ORDER BY D1
FOR XML PATH('')), 1, 1, '') as p1
FROM firstD1)
+
(select DISTINCT STUFF((SELECT ',' + CAST(D1 as varchar(100))
FROM other
FOR XML PATH('')), 1, 0, '') as p2
FROM other)