如何使用sql查询动态分组和拆分列?

时间:2017-08-24 08:15:04

标签: c# sql sql-server

我有一些表包含如下所示的行;

ID Date City     Income
1  2013 Kansas   10$
1  2013 Kansas   15$
1  2014 Kansas   30$
2  2013 Chicago  50$
...

我需要这样一个查询,将其转换为此;

ID Date City     Income1 Income2
1  2013 Kansas   10$     15$
1  2014 Kansas   30$
2  2013 Chicago  50$
...

所以我应该按ID分组,然后将收益值分成不同的列。 这就是我尝试实现它的方法,但有些事情不对;

select ID, DATE, MIN(CITY), CONCAT(INCOME,',') from [Sheet 1$] group by ID, DATE

1 个答案:

答案 0 :(得分:2)

Create table Table1(ID int, Year int, City Varchar(10), Income int)


Insert Into Table1 Values(1,  2013, 'Kansas',   10)
Insert Into Table1 Values(1,  2013, 'Kansas',   10)
Insert Into Table1 Values(1,  2013, 'Kansas',   15)
Insert Into Table1 Values(1,  2014, 'Kansas',  30)
Insert Into Table1 Values(2,  2013, 'Chicago',  50)

Select max(rn) as MaxCol
From(
        Select *, row_number() over(partition by ID,Year order by ID) as rn
        From Table1
    )as Tbl1


select *
from 
(
  Select *, row_number() over(partition by ID,Year order by ID) as rn
  from Table1
) src
pivot
(
  max(Income)
  for rn in ([1], [2], [3])
) piv;

实际上,当每年收入值(Count)的数量不固定时,动态sql是唯一的选择。

Link to a live demo on SQL Fiddle