在SQL中将多行合并为一行

时间:2012-08-26 22:10:51

标签: sql sql-server sql-server-2008 tsql

在sql server 2008中,我有一个包含[a],[b],[c],[sort]列的表,它有4条记录:

1,      NULL,  NULL    0
NULL,   2,     NULL    1
NULL,   NULL,  3       2
10,     NULL,  NULL    3

我需要以我得到一行的方式组合所有行,并且对于每一列,我得到第一个(按排序列排序)非空值。所以我的结果应该是:

1,      2,     3

有人可以建议怎么做吗? 感谢

1 个答案:

答案 0 :(得分:7)

单程

SELECT (SELECT TOP 1 [a]
        FROM   @T
        WHERE  [a] IS NOT NULL
        ORDER  BY [sort]) AS [a],
       (SELECT TOP 1 [b]
        FROM   @T
        WHERE  [b] IS NOT NULL
        ORDER  BY [sort]) AS [b],
       (SELECT TOP 1 [c]
        FROM   @T
        WHERE  [c] IS NOT NULL
        ORDER  BY [sort]) AS [c] 

或另一个

;WITH R
     AS (SELECT [a],
                [b],
                [c],
                [sort]
         FROM   @T
         WHERE  [sort] = 0
         UNION ALL
         SELECT Isnull(R.[a], T.[a]),
                Isnull(R.[b], T.[b]),
                Isnull(R.[c], T.[c]),
                T.[sort]
         FROM   @T T
                JOIN R
                  ON T.sort = R.sort + 1
                     AND ( R.[a] IS NULL
                            OR R.[b] IS NULL
                            OR R.[c] IS NULL ))
SELECT TOP 1 [a],
             [b],
             [c]
FROM   R
ORDER  BY [sort] DESC