如何将两个查询结果合并到一个表中

时间:2018-11-06 08:00:04

标签: mysql

我有两个查询,它们给出两个diff结果,两个结果表都有一个公共列,我想将它们合并,并且有一个结果表将公共列合并为一列

这是我的查询

    query1=  select b.CUSTOMERDESCRIPTOR as outlet,sum(a.netamount) as amount from syncbill a, ecustomer b where a.outlet=b.CUSTOMERIDENTIFIER and a.cancelled<>'Y' and year(curdate())=year(a.billdate) and month(curdate())=month(a.billdate) group by a.OUTLET;


 query2=   select b.CUSTOMERDESCRIPTOR as outlet,sum(a.netamount) as amount from syncbill a, ecustomer b where a.outlet=b.CUSTOMERIDENTIFIER and a.cancelled<>'Y' and year(curdate())=year(a.billdate) group by a.OUTLET;

第一个查询是给我这样的结果

this is the result i am getting from query1

第二个查询给我的结果是

[This is the result i am getting from querry2[2]

现在我要合并这两个查询以获得这样的结果

i want this kind of result

我尝试了合并,但是它重复了数据并仅显示两列的表。 请任何在那里有Mysql知识的人指导我如何实现这一目标

2 个答案:

答案 0 :(得分:1)

请在下面的查询中运行,您一次将获得两列

SELECT b.customerdescriptor AS outlet, 
       Sum(a.netamount)     AS currentYearAmount, 
       Sum(CASE 
             WHEN Month(Curdate()) = Month(a.billdate) THEN a.netamount 
             ELSE 0 
           end)             AS CurrentMonth 
FROM   syncbill a, 
       ecustomer b 
WHERE  a.outlet = b.customeridentifier 
       AND a.cancelled <> 'Y' 
       AND Year(Curdate()) = Year(a.billdate) 
GROUP  BY a.outlet; 

答案 1 :(得分:1)

Union是您所需要的

select 
    b.CUSTOMERDESCRIPTOR as outlet,
    sum(a.netamount) as amount 
from 
    syncbill a 
    Inner Join ecustomer b on a.outlet = b.CUSTOMERIDENTIFIER
where 
    a.cancelled<>'Y' and 
    year(curdate())=year(a.billdate) and 
    month(curdate())=month(a.billdate) 
group by 
    a.OUTLET;

Union

select 
    b.CUSTOMERDESCRIPTOR as outlet,
    sum(a.netamount) as amount 
from 
    syncbill a, 
    Inner Join ecustomer b on a.outlet=b.CUSTOMERIDENTIFIER
where 
    a.cancelled<>'Y' and 
    year(curdate())=year(a.billdate) 
group by 
    a.OUTLET;

请勿使用Implicit Join,而应使用CommaJoin不好,如果您不知道Join的工作方式,那么结果会很混乱。

但是为简单起见,您可以尝试:

select 
    b.CUSTOMERDESCRIPTOR as outlet,
    sum(case when month(curdate())=month(a.billdate) then a.netamount else 0 end) as monthAmount,
    sum(case when year(curdate())=year(a.billdate) then a.netamount else 0 end) as yearAmount 
from 
    syncbill a 
    Inner Join ecustomer b on a.outlet = b.CUSTOMERIDENTIFIER
where 
    a.cancelled<>'Y' 
group by 
    a.OUTLET;

我建议不要将ab用作别名表。为什么不给sb赋予syncbill并给{{ 1}} ..会说得通..

相关问题