gpt4 book ai didi

mysql - mysql select 查询中多个字段的求和问题

转载 作者:行者123 更新时间:2023-11-30 01:20:49 25 4
gpt4 key购买 nike

我有两个表rents和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

最佳答案

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

关于mysql - mysql select 查询中多个字段的求和问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18561423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com