如果左列包含null而右列不为空,则向左移动单元格

时间:2013-12-27 12:05:07

标签: sql

1 个答案:

答案 0 :(得分:0)

这样的东西
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

SQL Fiddle DEMO