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?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.