将两个连接查询合并为一个

时间:2013-10-28 06:21:32

标签: sql sql-server

我有两个想要合并为一个的查询。

第一个查询是

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

这不是我想要的。

请让我知道如何创建查询或表达式来实现此目的。

谢谢

1 个答案:

答案 0 :(得分:2)

您可以使用联接代替联盟。 在这种情况下,您的代码将如下所示:

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列排序。