如何将两个带有having子句的查询合并为一个?

时间:2016-01-07 14:18:35

标签: mysql sql having

我希望你能帮我解决这两个查询:

select count(distinct ID), sum(AMOUNT) 
from SALES 
where YEAR(SALEDATE) = '2015' and SALETYPE ='CASH'
group by CUSTOMER having sum(AMOUNT) >=500;

select count(distinct ID), sum(AMOUNT) 
from SALES 
where YEAR(SALEDATE) = '2015' and SALETYPE ='CREDITCARD'
group by CUSTOMER having sum(AMOUNT) >=1000;

将它们组合成一个的最佳方法是什么?我的目标是选择客户通过CREDITCARD支付超过500现金或超过1000的所有情况。

非常感谢你的帮助。

2 个答案:

答案 0 :(得分:2)

在您的情况下,您可以使用此示例:

select  count(distinct ID), 
        sum(AMOUNT) 
from    SALES 
where   YEAR(SALEDATE) = '2015' 
    and SALETYPE ='CASH' 
group by CUSTOMER 
having  sum(AMOUNT) >=500;

UNION

select  count(distinct ID), 
        sum(AMOUNT) 
from    SALES 
where   YEAR(SALEDATE) = '2015' 
    and SALETYPE ='CREDITCARD' 
group by CUSTOMER 
having  sum(AMOUNT) >=1000;

OR UNION ALL如果您想要所有没有不同的记录。

select  count(distinct ID), 
        sum(AMOUNT) 
from    SALES 
where   YEAR(SALEDATE) = '2015' 
    and SALETYPE ='CASH' 
group by CUSTOMER 
having  sum(AMOUNT) >=500;

UNION ALL

select  count(distinct ID), 
        sum(AMOUNT) 
from    SALES 
where   YEAR(SALEDATE) = '2015' 
        and SALETYPE ='CREDITCARD' 
group by CUSTOMER 
having  sum(AMOUNT) >=1000;

答案 1 :(得分:1)

having子句中使用条件聚合:

select count(distinct ID), sum(AMOUNT) 
from SALES 
where YEAR(SALEDATE) = '2015' and 
      SALETYPE IN ('CASH', 'CREDITCARD')
group by CUSTOMER
having sum(case when SALETYPE = 'CASH' then AMOUNT end) >= 50 OR
       sum(case when SALETYPE = 'CREDITCARD' then AMOUNT end) >= 1000;