4

In sql server 2008, I have a table that has the columns [a],[b],[c],[sort] and it has 4 records:

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

I need to combine all the rows in a way that i get one row as a result, and for each column I get the first (ordered by sort column) non-null value. So my result should be:

1,      2,     3

Can anyone suggest how to do this? Thanks

2
  • Does your table actually only have such a small amount of rows? If so might as well just use a simple solution such as three TOP queries. Commented Aug 26, 2012 at 22:18
  • It will definitely have a small amount of records. Most likely less than 10. Can you show an example of what you mean by three TOP queries? Commented Aug 26, 2012 at 22:19

1 Answer 1

7

One way

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] 

Or another

;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 
Sign up to request clarification or add additional context in comments.

1 Comment

+1 - I started with three subqueries, but changed my mind, but your solution is more inline with what was asked.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.