在Sql中我得到的结果如下格式。 我总共有6列。在第1行第6列包含值和第2行第5和第5列第6个包含值。但我需要检查每个单元格,如果前一列不包含值意味着我需要在第一列。
实际结果
a b c d e f
1
1 2
1 2 3
预期结果: -
a b c d e f
1
1 2
1 2 3
请发布一些好的答案(我使用的是SQL Server 2008-R2)
答案 0 :(得分:4)
另一种方式,类似于@Astander(但使用OUTER APPLY
代替PIVOT / UNPIVOT
):
SELECT
a = MIN(CASE WHEN y.rn = 1 THEN y.val END),
b = MIN(CASE WHEN y.rn = 2 THEN y.val END),
c = MIN(CASE WHEN y.rn = 3 THEN y.val END),
d = MIN(CASE WHEN y.rn = 4 THEN y.val END),
e = MIN(CASE WHEN y.rn = 5 THEN y.val END),
f = MIN(CASE WHEN y.rn = 6 THEN y.val END)
FROM t
OUTER APPLY
( SELECT
x.val,
rn = ROW_NUMBER() OVER (ORDER BY rn)
FROM
( VALUES
(a,1), (b,2), (c,3), (d,4), (e,5), (f,6)
) x (val, rn)
WHERE x.val IS NOT NULL
) y
GROUP BY
t.tid ;
中进行测试
答案 1 :(得分:2)
像
这样的东西DECLARE @Table TABLE(
a INT,
b INT,
c INT,
d INT,
e INT,
f INT
)
INSERT INTO @Table VALUES
(null,null,null,null,null,10),
(null,null,null,null,10,20),
(null,null,null,10,20,30)
SELECT *
FROM @Table
SELECT SUM([1]) a,
SUM([2]) b,
SUM([3]) c,
SUM([4]) d,
SUM([5]) e,
SUM([6]) f
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY ID ORDER BY (SELECT NULL)) ValID
FROM (
SELECT *,
ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) ID
FROM @Table
) p
UNPIVOT
(
val FOR col IN (a,b,c,d,e,f)
) up
) v
PIVOT (
SUM(val) FOR ValID IN ([1],[2],[3],[4],[5],[6])
) p
GROUP BY ID