Sql 分组依据以及同一查询中的总计
我有以下疑问Sql 分组依据以及同一查询中的总计,sql,oracle,Sql,Oracle,我有以下疑问 select role, count(*) as cases from ( select CASE WHEN r.id = 30 THEN r.name ELSE r.name || ' ' || u.member_id END AS role from case_inventory ci, users u, roles r where ci.board_id = u.board_id and ci.assigned_to = u.
select role, count(*) as cases from ( select
CASE WHEN r.id = 30 THEN r.name ELSE r.name || ' ' || u.member_id END AS role
from case_inventory ci, users u, roles r
where ci.board_id = u.board_id and
ci.assigned_to = u.io_id and
u.role_id = r.id
and ci.case_id = 40)
group by role;
输出为:
Role Cases
President 1
Student Member 2
我想在同一个查询中查询总数。我该如何前进
Role Cases
President 1
Student Member 2
Totals 3
您只需在查询中添加汇总即可重新编写查询:
select nvl(role, 'Totals') role, count(*) as cases from ( select
CASE WHEN r.id = 30 THEN r.name ELSE r.name || ' ' || u.member_id END AS role
from case_inventory ci, users u, roles r
where ci.board_id = u.board_id and
ci.assigned_to = u.io_id and
u.role_id = r.id
and ci.case_id = 40)
group by Rollup(role);
两件事:
- 切勿在
子句中使用逗号。始终使用正确、明确、标准、可读的连接语法FROM
- 限定查询中引用多个表的所有列引用
select coalesce(role, 'Total') as role, count(*) as cases
from (select (case when r.id = 30 then r.name else r.name || ' ' || u.member_id
end_ AS role
from case_inventory ci join
users u
on ci.board_id = u.board_id and
ci.assigned_to = u.io_id join
roles r
on u.role_id = r.id
where ci.case_id = 40
) r
group by grouping sets ( (role), () );
将
与ROLLUP一起使用@穿刺者得到了它。谢谢。您的查询在Oracle中不起作用。