Coalescing values in a column over a partition

狂风中的少年 提交于 2019-12-03 21:30:13

问题


I have chosen to ask this question via an example as I think it most clearly illustrates what I am trying to do.

Say I have the following table:

member   number  time
------   -----   -----
  1        2     19:21 
  1        4     19:24 
  1       27     19:37
  2        4     19:01
  2        7     21:56
  2        8     22:00
  2        21    22:01

How can I obtain the following column?

member   number  new column
------   -----   ---------
  1        2       2.4.27 
  1        4       2.4.27
  1       27       2.4.27
  2        4       4.7.8.21
  2        7       4.7.8.21
  2        8       4.7.8.21
  2       21       4.7.8.21

EDIT(S):

I am using DB2 SQL.

There is not necessarily the same number of rows for each member.

The order is determined by time say.


回答1:


depending on your version of db2, the LISTAGG() function may be available to you. i think it is included in any db2 version after 9.7.

example:

select
  member,
  number,
  listagg(number,',') as new_column
from
  tablename
group by
  member



回答2:


In Oracle this will do the job,

select a.member,a.number,b.newcol from table a,(select member,replace(wm_concat(number),',','.') newcol from test11 group by member)b where a.member=b.member;



回答3:


I know it's bad form answering your own question but I have found this useful page:

https://www.ibm.com/developerworks/mydeveloperworks/blogs/SQLTips4DB2LUW/entry/aggregating_strings42?lang=en

Modifying the code there gives:

create table test (member int, number int, time_stamp time)`;

insert into test values 
(1,2,'19:21'),
(1,4,'19:24'),
(1,27,'19:37'),
(2,4,'19:01'),
(2,7,'21:56'),
(2,8,'22:00'),
(2,21,'22:01');

select 
  member, substr(xmlcast(xmlgroup('.' || number as a order by time_stamp) as varchar(60)), 2)
from test
group by member


来源:https://stackoverflow.com/questions/13865657/coalescing-values-in-a-column-over-a-partition

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!