Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/oracle/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 分组依据以及同一查询中的总计_Sql_Oracle - Fatal编程技术网

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
    子句中使用逗号。始终使用正确、明确、标准、可读的连接语法
  • 限定查询中引用多个表的所有列引用
要在Oracle中回答您的问题,请使用分组集:

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中不起作用。