如何加入两个查询以获得单个查询的结果

How to join two queries to get result in single query

我有两个问题。从第一个开始,我得到了选定的年份和月份数据,从第二个查询中,我得到了上一年的数据,即去年

查询1: SELECT sum(a.netamount) NETAMOUNT,e.CUSTOMERDESCRIPTOR,YEAR(BILLDATE) AS DATEYEAR, MONTH (BILLDATE) DATEMONTH FROM syncbill a,ecustomer e WHERE a.OUTLET=e.CUSTOMERIDENTIFIER and YEAR(BILLDATE) = '2018' AND MONTH(BILLDATE) = '09' group by outlet

查询2: SELECT sum(a.netamount) NETAMOUNT,e.CUSTOMERDESCRIPTOR,YEAR(BILLDATE) AS DATEYEAR, MONTH (BILLDATE) DATEMONTH FROM syncbill a,ecustomer e WHERE a.OUTLET=e.CUSTOMERIDENTIFIER and YEAR(BILLDATE) = '2018-1' AND MONTH(BILLDATE) = '09' group by outlet

我正在使用 MySQL 5.5 并输入 year-1 来获取前一年的数据 就像 2018-1 给出 2017.

除了查询 1 中的年份是 2018 和查询 2 中的年份是 2018-1 i.e 2017.

之外,这两个查询之间的所有内容都是相同的

所以我想加入两个查询,这样我就可以在单个 运行.

中获取数据

因为2017年没有数据所以显示为空白,但我想改为显示0。

我知道我可以通过连接得到这个,但在这方面的经验非常有限。

SELECT sum(a.netamount) NETAMOUNT
,e.CUSTOMERDESCRIPTOR
,YEAR(BILLDATE) AS DATEYEAR
, MONTH (BILLDATE) DATEMONTH 
FROM syncbill a 
INNER JOIN ecustomer e ON a.OUTLET=e.CUSTOMERIDENTIFIER  
    and YEAR(BILLDATE) = '2018' AND MONTH(BILLDATE) = '09' 
group by outlet

UNION ALL

SELECT sum(a.netamount) NETAMOUNT
,e.CUSTOMERDESCRIPTOR,
YEAR(BILLDATE) AS DATEYEAR
, MONTH (BILLDATE) DATEMONTH 
FROM syncbill a
INNER JOIN ecustomer e ON  a.OUTLET=e.CUSTOMERIDENTIFIER 
    and YEAR(BILLDATE) = '2018-1' AND MONTH(BILLDATE) = '09' 
group by outlet

如果你想要两个分开的行,你可以使用 union all

UNION ALL return 始终是行结果

您也可以按年份使用单个查询组

    SELECT sum(a.netamount) NETAMOUNT
    ,e.CUSTOMERDESCRIPTOR
    ,YEAR(BILLDATE) AS DATEYEAR
    , MONTH (BILLDATE) DATEMONTH 
    FROM syncbill a 
    INNER JOIN ecustomer e ON a.OUTLET=e.CUSTOMERIDENTIFIER  
        and YEAR(BILLDATE) IN ('2018', '2018-1') AND MONTH(BILLDATE) = '09' 
    group by outlet, DATEYEAR, DATEMONTH