将列拆分/分隔成多列

时间:2018-01-11 09:27:38

标签: sql pivot crosstab

我完全卡住了,即使问题看起来很简单,我找不到任何问题的答案。我可以在不制作新表的情况下将该“描述”列分开吗?

现在我刚写了这个最简单的代码。

String[] arr = new String[];
Integer[] arr = new Integer[];

使用该代码,它看起来像这样:

select item_id, description
from data
where item_id = '123'

但我想让它看起来像这样:

item_id description
123     A
123     B
123     C

3 个答案:

答案 0 :(得分:0)

case表达式

的帮助下使用条件聚合
select item_id,
           max(case when description= 'A' then description end) [desc_1],
           max(case when description= 'B' then description end) [desc_2],
           max(case when description= 'C' then description end) [desc_3],
from table
group by item_id 

编辑:因此,动态数据透视方式与SQL Server一样

declare @col varchar(max), @q varchar(max)

set @col = stuff(
                    (select distinct ','+quotename('desc_'+cast(row_number() over(partition by Item_id order by description) as varchar)) 
                     from table for xml path('')),
                 1,1,'')

set @q = 'select * from
          (
              select *, 
                    ''desc_''+cast(row_number() over(partition by Item_id order by description) as varchar) rn 
              from table
          )a
          PIVOT
          (
               max(description) for rn in ('+@col+')
          )p'

EXEC (@Q)

结果:

item_id desc_1  desc_2  desc_3
123    A        B       C
234    B        C       d

答案 1 :(得分:0)

afs -- with clause name
giga -- alias name for listagg


with afs as
 (

select item_id,LISTAGG(description, ',') WITHIN GROUP (ORDER BY item_id) AS 
giga from test_jk group by item_id

)

select item_id,REGEXP_SUBSTR (giga, '[^,]+', 1, 1)    AS 
desc_1,REGEXP_SUBSTR (giga, '[^,]+', 1, 2)  as desc_2 from afs;

output

答案 2 :(得分:0)

首先声明不同的列名 像ABC,DEF,GHI 和价值观 然后写动态数据透视

handleAfterValidate