在SQL中使用带有分组方式的子选择

问题描述 投票:1回答:2

我正在尝试获取子选择查询以返回某些数据。为了方便起见,以下示例已简化:

期望的回报:

fullname    | total | total_pending
John Smith  |     5 |             1
Jane Bloggs |     2 |             0

数据在下表中:

org_users: id, fullnameorders: id, status, user_id

状态可以是订单的“待处理”或“完成”。

我这样写查询:

SELECT 
    ou.fullname,
    COUNT(o.*),
    ( 
       SELECT COUNT(*) 
       FROM orders oo 
       INNER JOIN org_users ouu ON ouu.id = oo.user_id 
       WHERE oo.status = 'pending'
       AND ouu.id = oo.user_id
    ) as pending_orders
FROM orders o
INNER JOIN org_users ou on ou.id = o.user_id
GROUP BY ou.id

但这只会为我返回此内容:

fullname    | total | total_pending
John Smith  |     5 |             7
Jane Bloggs |     2 |             7

我如何将子选择绑定到user_id上?自从我写原始SQL以来已经有一段时间了,所以我很难做到这一点

sql
2个回答
1
投票

使用条件聚合:

SELECT ou.fullname, COUNT(*),
       SUM(CASE WHEN o.status = 'pending' THEN 1 ELSE 0 END) as num_pending
FROM orders o INNER JOIN
     org_users ou 
     ON ou.id = o.user_id
GROUP BY ou.id, ou.fullname;

1
投票

我认为如果在聚合中使用case表达式会更有效

select
    ou.fullname,
    count(*),
    sum(case when oo.status = 'pending' then 1 else 0 end) as pending_orders
from orders as o
    inner join org_users as ou on
        ou.id = o.user_id
group by
    ou.fullname
© www.soinside.com 2019 - 2024. All rights reserved.