Mysql两个条件就是总共一列

时间:2018-02-19 18:46:44

标签: mysql sql

我有一个表suspended_bills,我希望得到总数的总和,但我希望在一个查询中得到总数。检查此查询

SELECT  date, (select sum(total) where type='bill') as bill_total, (select 
sum(total) where type='quotation') as quotation_total from suspended_bills 
group by YEAR(date),MONTH(date)

我知道这是错误的查询,但我想知道在单个查询中获取帐单和报价总和的解决方案。

1 个答案:

答案 0 :(得分:2)

我认为你想要条件聚合:

select YEAR(date), MONTH(date), 
       sum(case when type = 'bill' then total else 0 end) as bill_total, 
       sum(case when type = 'quotation' then total else 0 end) as quotation_total
from suspended_bills 
group by YEAR(date), MONTH(date);