【问题标题】:Sum Issue with multiple fields in mysql select querymysql select查询中多个字段的求和问题
【发布时间】:2013-09-01 18:18:17
【问题描述】:

我有两个表rentals和sales。有一个字段status。如果status=1是unpublish,status=2是publish,status=3是pending。

我想查找代理的所有已发布、取消发布和待定租赁和销售的总和。

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

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

【问题讨论】:

    标签: mysql select sum union


    【解决方案1】:

    根据您对问题的描述,您的查询看起来是正确的。这是编写查询的另一种方式。它只是在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;
    

    【讨论】:

      猜你喜欢
      • 2020-09-30
      • 1970-01-01
      • 2018-08-30
      • 2011-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多