简体   繁体   English

分组依据以及同一查询中的总计

[英]group by along with totals in the same query

I have the below query我有以下查询

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;

Output is: Output 是:

  Role          Cases
  President      1
  Student Member 2  

I want the totals in the same query.我想要同一查询中的总数。 How should I go forward?我应该如何转发go?

  Role          Cases
  President      1
  Student Member 2  
  Totals         3

You can simply rewrire your query by adding rollup in the query:您可以通过在查询中添加汇总来简单地重新编写查询:

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);

Two things:两件事情:

  • Never use commas in the FROM clause.切勿FROM子句中使用逗号。 Always use proper, explicit, standard , readable JOIN syntax.始终使用正确、明确、标准、可读的JOIN语法。
  • Qualify all column references in a query that references more than one table.限定引用多个表的查询中的所有列引用。

To answer your question in Oracle , use grouping sets :要回答您在 Oracle中的问题,请使用grouping sets

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), () );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM