以下使用內部聯接的查詢回傳name兩個表中匹配的總和。
;with cte1 as
(
select 'a' as 'name', 1 as 'total'
union
select 'b', 2
union
select 'x', 6
union
select 'y', 7
union
select 'z', 8
union
select 'f', 30
),
cte2 as
(
select 'a' as 'name', 11 as 'total'
union
select 'b', 22
union
select 'd', 6
union
select 'y', 7
union
select 'z', 8
)
select cte1.name, cte1.total cte2.total as 'total'
from cte1 inner join cte2 on
cte1.name = cte2.name
結果是:
name total total total
a 1 11 12
b 2 22 24
y 7 7 14
z 8 8 16
即使沒有匹配,我也需要顯示總數,所以結果應該如下所示(“n/a”只是為了顯示 cte 中不存在值):
name cte1.total cte2.total total
a 1 11 12
b 2 22 24
y 7 7 14
z 8 8 16
f 30 n/a 30
x 6 n/a 6
d n/a 6 6
值 'x' 和 'f' 不在 cte2 中,但它們包含在總數中。'd' 不在 cte1 中,但我們也看到了總數。
uj5u.com熱心網友回復:
您可以使用
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/362300.html
標籤:sql-server 查询语句
