从汇总中获取所需的输出

Getting desired output from Rollup

你能帮我得到下面的输出吗

数据脚本

        create table temp(id number,first_name varchar2(10),last_name varchar2(10),order_id varchar2(2));
            insert into temp values(1,'Ram1','Shayam1','O1');
            insert into temp values(1,'Ram1','Shayam1','O2');
            insert into temp values(2,'Ram2','Shayam2','O1');
            insert into temp values(2,'Ram2','Shayam2','O2');
            insert into temp values(3,'Ram3','Shayam3','O1');
            insert into temp values(4,'Ram4','Shayam4','O1');
            insert into temp values(4,'Ram4','Shayam4','O2');
            insert into temp values(4,'Ram4','Shayam4','O3');
            insert into temp values(5,'Ram5','Shayam5','O1');
            insert into temp values(5,'Ram5','Shayam5','O2');
            insert into temp values(5,'Ram5','Shayam5','O3');
            insert into temp values(6,'Ram6','Shayam6','O1');
            insert into temp values(7,'Ram7','Shayam7','O1');

输出

id   first_name   last_name  order_id  count
--------------------------------------------
1      Ram1        Shayam1    O1       1
1      Ram1        Shayam1    O2       1
1                                      2  --total number of id,grp by id
2      Ram2        Shayam2    O1       1
2      Ram2        Shayam2    O2       1
2                                      2
3      Ram3        Shayam3    O1       1
3                                      1
4      Ram4        Shayam4    O1       1
4      Ram4        Shayam4    O2       1
4      Ram4        Shayam4    O3       1
4                                      3
5      Ram5        Shayam5    O1       1
5      Ram5        Shayam5    O2       1
5      Ram5        Shayam5    O3       1
5      Ram5        Shayam5    O4       1
5                                      4
6      Ram6        Shayam6    O1       1
6                                      1      
7      Ram7        Shayam7    O1       1
7                                      1
                                       7  --total distinct id

我尝试过使用 rollup,但我无法通过 rollup 获得最后一个总的不同 ID

SQLFIDDLE

根据你想要的输出应该是这样的:

SELECT id,
  first_name,
  last_name,
  order_id,
  CASE
    WHEN grouping(id) = 1
    THEN COUNT(DISTINCT id)
    ELSE COUNT(*)
  END res
FROM temp
GROUP BY grouping sets ((id ,first_name ,last_name ,order_id),(id),());

试试下面的代码,希望你能满意我的回答。

 select id,max(first_name),max(last_name),order_id,count(order_id) from temp
    where id is not null
    group by cube(id,order_id)
    order by id