您能否帮助我获得以下输出
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
我尝试过使用汇总,但是我无法使用汇总实现最后一个完全不同的ID
答案 0 :(得分:2)
根据您想要的输出,它应该是这样的:
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),());
答案 1 :(得分:0)
尝试使用贝娄代码,希望您能满意我的回答。
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