2012-08-26 67 views
4

在SQL Server 2008中,我有了列[A],[B],[C],[分頁]表中,它有4條:將多個行成一個在SQL

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

我需要結合所有的行,我得到一行作爲結果,併爲每個列我得到第一個(按排序列排序)非空值。所以我的結果應該是:

1,  2,  3 

任何人都可以建議如何做到這一點? 感謝

+0

貴表實際上只有行這麼小的量?如果可以的話,只需使用一個簡單的解決方案,如三個「TOP」查詢。 –

+0

它肯定會有少量的記錄。最有可能少於10個。你能舉三個TOP查詢的例子嗎? – BlueChameleon

回答

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 
+0

+1 - 我從三個子查詢開始,但改變了主意,但您的解決方案更符合要求。 –

+0

工程就像一個魅力。謝謝 – BlueChameleon

+3

+1。這裏是小提琴:http://sqlfiddle.com/#!3/fd607/1/0 –