[英]Combining two join queries into one
I have two queries that I want to combine into one. 我有两个查询要合并为一个。
First query is 第一个查询是
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;
It returns following result 返回以下结果
desc amount
NW 12.00
SW 10
Second query I have 我有第二个查询
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;
This query returns this result: 该查询返回以下结果:
desc amount
NW 4.00
I want to combine these two queries so that I get out put like this.. 我想将这两个查询结合起来,这样我就可以放心了。
desc amount amount1
NW l2.00 4.00
SW 10.00
I tried UNION
between query 1 and query 2 but the result came out as 我在查询1和查询2之间尝试了UNION
,但结果显示为
desc amountamount1
NW 16.00
SW 10.00
Which is not what I wanted. 这不是我想要的。
Please let me know how I can create a query or expression to achieve this. 请让我知道如何创建查询或表达式来实现此目的。
Thanks 谢谢
Instead of union you can use the join. 除了联合,您可以使用联接。 In this case your code will be like the following: 在这种情况下,您的代码将如下所示:
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
Because of the same table usage for the desc
column source, coalesce function can be used. 由于desc
列源的表用法相同,因此可以使用合并功能。 The result query will be ordered by the result desc
column. 结果查询将按结果desc
列排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.