2009-01-28 69 views
0

合併的結果我有疑問:在T-SQL語句

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 

我要輸出到這些結合起來,也許像數據透視表,使用T-SQL。


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

這怎麼寫?

+0

您有哪些版本的SQL Server? – 2009-01-28 15:39:12

回答

3

無需樞軸。

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是ANSI SQL,但你可以使用ISNULL太