是否可以使用 join 按列分组?

问题描述 投票:0回答:1
select tc.UIDPK,
count(torder.status) as total
from TCUSTOMER tc
inner join TORDER torder on tc.UIDPK=torder.CUSTOMER_UID
where tc.UIDPK=490000;

上面的查询对我来说很好用。 但是状态可以是 IN_PROGRESS、FAILED、ON_HOLD

我如何编写返回状态计数的查询 喜欢 tc.UIDPK, count of total orders, count of IN_PROGRESS orders, count of total orders-count of IN_PROGRESS orders. 我在下面试过但没有用

select tc.UIDPK,
count(torder.status) as total,
count(torder2.status) as inprogress,
count(torder.status)-count(torder2.status) as remaining
from TCUSTOMER tc
inner join TORDER torder on tc.UIDPK=torder.CUSTOMER_UID
left join TORDER torder2 on tc.UIDPK=torder2.CUSTOMER_UID and torder2.status in('IN_PROGRESS')
where tc.UIDPK=490000;
sql mysql pivot aggregate-functions
1个回答
2
投票

不需要多重连接,使用SUM。

试试

select tc.UIDPK,
       COUNT(torder.status) as total,
       SUM(torder.status = 'IN_PROGRESS') as inprogress,
       COUNT(torder.status) - SUM(torder.status = 'IN_PROGRESS') as remaining
from TCUSTOMER tc
inner join TORDER torder on tc.UIDPK=torder.CUSTOMER_UID
where tc.UIDPK=490000
group by tc.UIDPK;
© www.soinside.com 2019 - 2024. All rights reserved.