views:

229

answers:

1

I have to queries:

select id, name, num from pending  

id, name, num
1, first, 1  
3, third, 12  
select id, name, num from completed

id, name, num
1, first, 100
2, second, 20

I want output to combine these, maybe like a pivot table, using T-SQL.


id, name, pending, completed, total
1, first, 1, 100, 101
2, second, null, 20, 20
3, third, 12, null, 12

How can this be written?

+3  A: 

No need for a pivot.

SELECT
    COALESCE(p.id, c.id),
    COALESCE(p.name, c.name),
    p.num AS pending,
    c.num AS completed,
    COALESCE (p.num, 0) + COALESCE (c.num, 0) AS total
FROM
    pending p
    FULL OUTER JOIN
    completed c ON p.id = c.id

COALESCE is ANSI SQL but you could use ISNULL too

gbn