2017-08-24 164 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