在SQL中使用带有group by的子选择
我正在尝试获取一个子选择查询以返回某些数据。为方便起见,简化了以下示例: 期望回报:在SQL中使用带有group by的子选择,sql,Sql,我正在尝试获取一个子选择查询以返回某些数据。为方便起见,简化了以下示例: 期望回报: fullname | total | total_pending John Smith | 5 | 1 Jane Bloggs | 2 | 0 数据如下表所示: org\u用户:id,全名 订单:id、状态、用户id 订单上的状态可以是“待定”或“完成” 我这样写我的查询: SELECT ou.fullname, COU
fullname | total | total_pending
John Smith | 5 | 1
Jane Bloggs | 2 | 0
数据如下表所示:
org\u用户:id,全名
订单:id、状态、用户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
当用户id进行计数时,如何使我的subselect绑定到该用户id?我已经有一段时间没有编写原始SQL了,所以我很难正确理解它我认为如果在聚合中使用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
使用条件聚合:
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;
这对我有用!非常感谢你。当我有能力时(6分钟后),我会将答案标记为正确