[英]Combining two join queries into one
我有兩個查詢要合並為一個。
第一個查詢是
select
a.desc as desc
,sum(bdd.amount) as amount
from
t_main c
left outer join
t_direct bds on (bds.mainId = c.id)
left outer join
tm_defination a on (a.id = bds.defId)
where
c.descId = 1000000134
group by
a.desc;
返回以下結果
desc amount
NW 12.00
SW 10
我有第二個查詢
select
a.desc as desc
,sum(bdd.newAmt) as amount1
from
t_main c
left outer join
t_newBox b on (b.mainId = c.id)
left outer join
t_transition c on (c.id = b.tranId)
left outer join
tm_defination def a on (a.id = c.defId)
where
c.descId = 1000000134
group by
a.desc;
該查詢返回以下結果:
desc amount
NW 4.00
我想將這兩個查詢結合起來,這樣我就可以放心了。
desc amount amount1
NW l2.00 4.00
SW 10.00
我在查詢1和查詢2之間嘗試了UNION
,但結果顯示為
desc amountamount1
NW 16.00
SW 10.00
這不是我想要的。
請讓我知道如何創建查詢或表達式來實現此目的。
謝謝
除了聯合,您可以使用聯接。 在這種情況下,您的代碼將如下所示:
select coalesce(q1.desc, q2.desc) as desc,
q1.amount as amount, q2.amount1 as amount1
from
(
select
a.desc as desc
,sum(bdd.amount) as amount
from t_main c
left outer join t_direct bds on (bds.mainId=c.id)
left outer join tm_defination a on (a.id =bds.defId)
where c.descId=1000000134
group by a.desc
) q1
full join
(
select
a.desc as desc
,sum(bdd.newAmt) as amount1
from t_main c
left outer join t_newBox b on (b.mainId=c.id)
left outer join t_transition c (c.id=b.tranId)
left outer join tm_defination def a on (a.id =c.defId)
where c.descId=1000000134
group by a.desc
) q2
on q1.desc = q2.desc
order by 1
由於desc
列源的表用法相同,因此可以使用合並功能。 結果查詢將按結果desc
列排序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.