Oracle - SQL在一组值完成后添加一行

时间:2018-04-06 08:02:39

标签: sql oracle oracle11g oracle10g oracle-sqldeveloper

CREATE TABLE "OPERATE" ("SQL_ID" VARCHAR2(13 BYTE), "CHILD_NUMBER" NUMBER, "COMMAND_TYPE" NUMBER );
Insert into OPERATE (SQL_ID,CHILD_NUMBER,COMMAND_TYPE) values ('6z0vqndtyx6w4',211,2);
Insert into OPERATE (SQL_ID,CHILD_NUMBER,COMMAND_TYPE) values ('74jdcz9vdg9dw',0,2);
Insert into OPERATE (SQL_ID,CHILD_NUMBER,COMMAND_TYPE) values ('097nk49ptumbm',1,2);
Insert into OPERATE (SQL_ID,CHILD_NUMBER,COMMAND_TYPE) values ('00jchz9tqxqwg',1,3);
Insert into OPERATE (SQL_ID,CHILD_NUMBER,COMMAND_TYPE) values ('00qxnvf7p1sxg',0,3);
Insert into OPERATE (SQL_ID,CHILD_NUMBER,COMMAND_TYPE) values ('1awzurfqvtf32',0,6);
Insert into OPERATE (SQL_ID,CHILD_NUMBER,COMMAND_TYPE) values ('3zzqvtya411wb',0,6); commit;

select * from operate;

output:
COMMAND_TYPE, SQL_ID, CHILD_NUMBER
2   6z0vqndtyx6w4   211
2   74jdcz9vdg9dw   0
2   097nk49ptumbm   1
3   00jchz9tqxqwg   1
3   00qxnvf7p1sxg   0
6   1awzurfqvtf32   0
6   3zzqvtya411wb   0

Expecting:
COMMAND_TYPE, SQL_ID, CHILD_NUMBER
2   6z0vqndtyx6w4   211
2   74jdcz9vdg9dw   0
2   097nk49ptumbm   1
2   2               2 **-- want to print value of command_type (in each column or one column, there are total 3 columns) once all the rows of a command_type have come (as shown in o/p), command_type values are dynamic, pls suggest.**
3   00jchz9tqxqwg   1
3   00qxnvf7p1sxg   0
3   3               3 **--** 
6   1awzurfqvtf32   0
6   3zzqvtya411wb   0
6   6               6 **--** 

请建议。我在上面的输出中提出了这个问题。 必须再次写这个来发布它"一旦command_type的所有行都来了,想要打印command_type的值(在每列或一列中,共有3列)(如o / p所示), command_type值是动态的"

3 个答案:

答案 0 :(得分:3)

您可以应用GROUPING SETS:

select
   COMMAND_TYPE, SQL_ID,CHILD_NUMBER
from operate
group by grouping sets
  ((COMMAND_TYPE, SQL_ID, CHILD_NUMBER),
   (COMMAND_TYPE));
order by 1

这将为SQL_ID和CHILD_NUMBER返回NULL,如果您确实需要重复COMMAND_TYPE,则必须应用COALESCE

顺便说一句,显示数据通常在客户端处理。

答案 1 :(得分:0)

您可以尝试以下查询:

select COMMAND_TYPE,
nvl(SQL_ID,COMMAND_TYPE) sql_id,
nvl(CHILD_NUMBER,command_type)CHILD_NUMBER
FROM (
select COMMAND_TYPE, SQL_ID,CHILD_NUMBER
from operate
union all
select distinct command_Type, null ,null
from operate)
order by command_type, child_number nulls last;

答案 2 :(得分:0)

使用类似的分析功能:

select t1.a command_type,
       t1.b sql_id,
       t1.c child_number
       from (
            select COMMAND_TYPE a, nvl(SQL_ID,command_type) b, nvl(CHILD_NUMBER,command_type) c, grouping_id(COMMAND_TYPE, SQL_ID,CHILD_NUMBER) from test_operate
            group by cube(COMMAND_TYPE,SQL_ID,CHILD_NUMBER)
            having (child_number is not null and command_type is not null and SQL_ID is not null)
            or (child_number is  null and command_type is  not null and sql_id is null)
            order by 1,4
)t1

我认为你可以找到简单的方法,但我希望这个决心能为你提供良好的指导。