1

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

第一个查询是

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  

UNION在查询 1 和查询 2 之间进行了尝试,但结果显示为

            desc    amountamount1
             NW      16.00
             SW      10.00

这不是我想要的。

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

谢谢

4

1 回答 1

2

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. The result query will be ordered by the result desc column.

于 2013-10-28T06:35:14.847 回答