2017-08-24 64 views
0

我有一些表包含像下面的行;如何使用sql查询动态分组和动态分列?

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 
+2

每个城市和年份的条目数是固定的还是可变的?如果是后者,那么你可能需要动态SQL来处理它。 –

+0

固定,不要使用变量,我需要单个镜头 – TyForHelpDude

+1

[如何使用通过C#在Excel中查询使用组可能重复](https://stackoverflow.com/questions/45855840/how-to-use-group-by-查询在excel-via-c-sharp)你已经在stackoverflow上有这个问题 - 当然你需要决定你的数据在哪里 - 因为这与 – BugFinder

回答

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; 

其实动态SQL是当每年的收入值(计数)的数量是不固定的唯一选择。

Link to a live demo on SQL Fiddle

+1

我同意,问题是接近这一个:https://stackoverflow.com/questions/10404348/sql-server-dynamic-pivot-query。你无法摆脱它没有变数。 – Exomus

+0

是的,现在有道理,谢谢 – TyForHelpDude