我正在尝试将行转换为列,按唯一标识符(CASE_ID)进行分组。
我有一个具有这种结构的表:
CASE_ID..AMOUNT..TYPE
100 ........ 10 .......甲
100 ........ 50 .......乙
100 ........ 75 .......甲
200 ........ 33 .......乙
200 ........ 10 ....... C
我正在尝试查询它以产生这种结构......
... CASE_ID ... AMOUNT_1 ... TYPE_1 ... AMOUNT_2 ... TYPE_2 ... AMOUNT_3
TYPE_3
100 ........... 10 ..................甲............. 50 .... ..............乙............. 75 ................... A <登记/>
200 ........... 33 ..................乙............. 10 .... .............. C ............(null)...............(null)
(假设有更大的数据集,包含CASE_ID,TYPE和AMOUNT的大量可能值)
我尝试使用pivot但我不需要聚合函数(只是尝试重组数据)。现在我试图以某种方式使用row_number但不确定如何。
我基本上是在尝试复制和SPSS命令叫做Casestovars,但是需要能够在SQL中执行它。感谢。
答案 0 :(得分:6)
您可以通过使用row_number()
创建序列号来获得结果,然后使用带有CASE表达式的聚合函数:
select case_id,
max(case when seq = 1 then amount end) amount1,
max(case when seq = 1 then type end) type1,
max(case when seq = 2 then amount end) amount2,
max(case when seq = 2 then type end) type2,
max(case when seq = 3 then amount end) amount3,
max(case when seq = 3 then type end) type3
from
(
select case_id, amount, type,
row_number() over(partition by case_id
order by case_id) seq
from yourtable
) d
group by case_id;
如果您使用的是具有PIVOT功能的数据库产品,那么您可以将row_number()
与PIVOT一起使用,但首先我建议您先将amount
和type
列取消。 SQL Server中有限数量值的基本语法是:
select case_id, amount1, type1, amount2, type2, amount3, type3
from
(
select case_id, col+cast(seq as varchar(10)) as col, value
from
(
select case_id, amount, type,
row_number() over(partition by case_id
order by case_id) seq
from yourtable
) d
cross apply
(
select 'amount', cast(amount as varchar(20)) union all
select 'type', type
) c (col, value)
) src
pivot
(
max(value)
for col in (amount1, type1, amount2, type2, amount3, type3)
) piv;
如果您有一个未知数量的值,那么您可以使用动态SQL来获得结果 - SQL Server语法将是:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(col+cast(seq as varchar(10)))
from
(
select row_number() over(partition by case_id
order by case_id) seq
from yourtable
) d
cross apply
(
select 'amount', 1 union all
select 'type', 2
) c (col, so)
group by col, so
order by seq, so
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT case_id,' + @cols + '
from
(
select case_id, col+cast(seq as varchar(10)) as col, value
from
(
select case_id, amount, type,
row_number() over(partition by case_id
order by case_id) seq
from yourtable
) d
cross apply
(
select ''amount'', cast(amount as varchar(20)) union all
select ''type'', type
) c (col, value)
) x
pivot
(
max(value)
for col in (' + @cols + ')
) p '
execute sp_executesql @query;
见SQL Fiddle with Demo。每个版本都会给出结果:
| CASE_ID | AMOUNT1 | TYPE1 | AMOUNT2 | TYPE2 | AMOUNT3 | TYPE3 |
|---------|---------|-------|---------|-------|---------|--------|
| 100 | 10 | A | 50 | B | 75 | A |
| 200 | 33 | B | 10 | C | (null) | (null) |