【发布时间】: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
【问题讨论】: