如何连接多行的字符串?

时间:2017-03-27 17:24:44

标签: sql oracle

我有一个包含以下列的表:

  • 产品
  • YEAR_UPDATED

示例数据:

PROD1,2017
PROD1,2015
PROD2,2014
PROD3,2017

如何获取每个产品更新时间的列表?类似的东西:

PRODUCT,2017,2016,2015,2014,etc
PROD1,Y,N,Y,N
PROD2,N,N,N,Y
PROD3,Y,N,N,N

PROD1,2017,2015
PROD2,2014
PROD3,2017

Oracle DB

谢谢!

2 个答案:

答案 0 :(得分:3)

我假设该表的名称为Products,将其更改为您的表名称。

<强>的Oracle

您可以使用LISTAGG function来实现它。

select p.Product || ', ' || listagg(p.YEARUPDATED,',') within group (order by p.YEARUPDATED)
from Products p
group by p.Product;

如果您使用的是 SQL Server ,则可以使用此方法。

select p.Product + ', ' + stuff((select ', '+ cast(tp.YearUpdated as varchar(4)) from Products tp where p.Product = tp.Product
          FOR XML PATH('')) , 1, 2, '')
from Products p
group by p.Product

如果您想快速测试它,可以尝试一下(使用内存表)。

declare @Products table (Product varchar(50), YearUpdated int);

insert into @Products values ('Product 1', 2000);
insert into @Products values ('Product 1', 2001);
insert into @Products values ('Product 1', 2002);
insert into @Products values ('Product 1', 2003);
insert into @Products values ('Product 2', 2010);
insert into @Products values ('Product 2', 2011);
insert into @Products values ('Product 4', 2012);
insert into @Products values ('Product 4', 2013);
insert into @Products values ('Product 4', 2015);
insert into @Products values ('Product 3', 2005);

select p.Product + ', ' + stuff((select ', '+ cast(tp.YearUpdated as varchar(4)) from @Products tp where p.Product = tp.Product
          FOR XML PATH('')) , 1, 2, '')
from @Products p
group by p.Product

答案 1 :(得分:1)

假设您的表中有id和year列:

   select cast ( t1.id as  varchar) + ',' + ( case when  t1.rn2 = 1   then  '2015' else '' end )
+ 
   ( case when  t1.rn2 = 2  then  '2015,2016 ' else  '' end ) + 
   ( case when  t1.rn2 =  3 then  '2015,2016,2017' else '' end ) 
 from 
  (select distinct  yourTBL.id , max(yourTBL.rn)
   over ( partition by yourTBL.id order by yourTBL.year rows BETWEEN  UNBOUNDED PRECEDING 
        AND UNBOUNDED following ) as rn2
 from (select id ,  year ,  
      row_number()over (partition by id order by year) as rn from yourTBL ) t) t1