SQL Listagg作为额外的列

时间:2018-10-11 13:27:00

标签: sql oracle listagg

我正在寻找一个聚合SQL列的Oracle SQL查询,但是将聚合添加为额外的列,而不是“真正地”聚合行。因此,我想以完全相同的行数结束,并使用带有汇总值的额外列。以下示例应有助于说明我的意思。

起始桌:

ID    GIVEN_NAME   LAST_NAME
11    CARL         CLARKE
22    CARL         CLARKE
33    CARL         CLARKE
44    ANDREW       JOHNSON
55    ANDREW       JOHNSON

GIVEN_NAME和LAST_NAME组成的常规listagg(ID)组会给我:

LISTAGG(ID)   GIVEN_NAME   LAST_NAME
112233        CARL         CLARKE
4455          ANDREW       JOHNSON

我想要的只是添加一个聚合列:

AGGREGATE   ID    GIVEN_NAME   LAST_NAME
112233      11    CARL         CLARKE
112233      22    CARL         CLARKE
112233      33    CARL         CLARKE
4455        44    ANDREW       JOHNSON
4455        55    ANDREW       JOHNSON

这甚至可能吗?谢谢!

4 个答案:

答案 0 :(得分:1)

analytic form中使用LISTAGG函数(OVER(分析子句)):

select GIVEN_NAME, LAST_NAME,
    LISTAGG(ID) WITHIN GROUP (ORDER BY ID) OVER (PARTITION BY department_id) as "AGGREGATE"
  from SOMETABLE

另请参阅Analytic example in LISTAGG documentation

答案 1 :(得分:0)

这是使用listagg的一种选择:

with sample_data as (
    select level     id,level given_name,level last_name from dual connect by level <= 10
    union all
    select level+30  id,level given_name,level last_name from dual connect by level <= 5
    union all
    select level+500 id,level given_name,level last_name from dual connect by level <= 3
    order by id
)
select 
    (select listagg(id) within group (order by id) 
     from sample_data di 
     where di.given_name=d.given_name and di.last_name=d.last_name) aggregate
    ,d.* 
    from sample_data d
 ;

答案 2 :(得分:0)

LISTAGG是聚合和分析的两个选项。

您正在寻找分析选项:

汇总功能

select name, listagg(id) within group (order by id)  as lst
from tab
group by name;

NAME LST 
---- ------
X    1112   
Y    1314

分析功能

请注意,OVER子句使用PARTITION BY表示分组键。

select name, id, listagg(id) within group (order by id) over( partition by name)  as lst
from tab;


NAME         ID LST  
---- ---------- -------
X            11 1112    
X            12 1112    
Y            13 1314     
Y            14 1314 

答案 3 :(得分:0)

这将起作用:

create table table123(col1 varchar(20),col2 varchar(20),col3 varchar(20)) 
insert into table123 values('11' ,   'CARL'   ,      'CLARKE');
insert into table123 values('22'  ,  'CARL'    ,     'CLARKE');
insert into table123 values('33'  ,  'CARL'    ,    'CLARKE');
insert into table123 values('44'  ,  'ANDREW'  ,     'JOHNSON');
insert into table123 values('55'  ,  'ANDREW'  ,     'JOHNSON');
SELECT * FROM table123;

SELECT a.col1,a.col2,a.col3,(select LISTAGG(col1, '') WITHIN GROUP (ORDER BY 
col2) "aggreaget" from table123 where col2=a.col2 group by col2 ) 
FROM table123 a group by a.col2,a.col1,a.col3 order by a.col1

示例输出:

11  CARL    CLARKE  112233
22  CARL    CLARKE  112233
33  CARL    CLARKE  112233
44  ANDREW  JOHNSON 4455
55  ANDREW  JOHNSON 4455