在mysql选择查询中的多个字段的Sum问题

时间:2013-09-01 18:18:18

标签: mysql select sum union

我有两个表租赁和销售。有一个字段状态。如果status = 1取消发布,status = 2是发布,status = 3正在等待。

我想在代理商的租金和销售中找到所有发布,取消发布和待处理的总和。

这是我尝试的但它给了我错误的数据

select sum(publish1) publish, sum(unpublish1) unpublish, sum(pending1) pending, agent_id,status from ( 

select agent_id,status, count(*) as publish1, 0 unpublish1, 0 pending1 from rentals where status = 2  GROUP BY agent_id 

union all select agent_id,status, 0 publish1, count(*) as unpublish1, 0 pending1 from rentals where status = 1  GROUP BY agent_id 

union all select agent_id,status, 0 publish1, 0 pending1, count(*) as pending1 from rentals where status = 3 GROUP BY agent_id 

union all select agent_id,status, count(*) as publish1, 0 unpublish1, 0 pending1 from sales where status = 2  GROUP BY agent_id 

union all select agent_id,status, 0 publish1, count(*) as unpublish1, 0 pending1 from sales where status = 1 GROUP BY agent_id 

union all select agent_id,status, 0 publish1, 0 pending1, count(*) as pending1 from sales where status = 3  GROUP BY agent_id ) s GROUP BY agent_id

1 个答案:

答案 0 :(得分:0)

根据您对问题的描述,您的查询看起来正确。这是编写查询的另一种方法。它只是在union

之前进行聚合
select agent_id,
       sum(case when status = 2 then val else 0 end) as publish,
       sum(case when status = 1 then val else 0 end) as unpublish,
       sum(case when status = 3 then val end) as pending
from ((select status, agent_id, status, count(*) as val
       from rentals
       where status in (2, 1, 3)
       group by status, agent_id 
      ) union all
      (select status, agent_id, count(*) as val
       from sales
       where status in (2, 1, 3)
       group by status, agent_id
      )
     ) t
group by agent_id;