2017-01-25 89 views
1

您好我有我的表中的數據是這樣的:的SQL Server PIVOT多個日期

Herd | Tag | Byr | Mob | Date  | Trait | Value 
-----|-----|-----|-----|-------------|-------|------- 
6002 | 1/08| 2008| 1 | 2015-08-17 | LWT | 425 
6002 | 1/08| 2008| 3 | 2015-12-22 | LWT | 516 
6002 | 1/08| 2008| 4 | 2016-04-06 | LWT | 688 

我需要從長期使用旋轉功能

Herd | Tag | Byr | Mob | 2015-08-17 | Mob | 2015-12-22 | Mob | 2016-04-06 
-----|-----|-----|-----|------------|-----|------------|-----|------------ 
6002 | 1/08| 2008| 1 | 425  | 3 | 516  | 4 | 688 

任何幫助將改爲寬幅十分讚賞

+0

我也有多個日期(數百)。 – proctor

回答

1

這裏是一個動態樞軸多個列

Declare @SQL varchar(max) 
Set @SQL = Stuff((Select Distinct ',' +QuoteName(concat('Mob_',Date))+' as Mob,'+QuoteName(Date) 
        From Yourtable 
        Order by 1 
        For XML Path('')),1,1,'') 

Select @SQL = ' 
Select [Herd],[Tag],[Byr],' + @SQL + ' 
From (
     Select [Herd],[Tag],[Byr] 
       ,B.* 
     From YourTable A 
     Cross Apply (
        Values (concat(''Mob_'',A.Date),cast(A.Mob as nvarchar(50))) 
          ,(concat('''',A.Date) ,cast(A.Value as nvarchar(50))) 
        ) B (Item,Value) 
    ) A 
Pivot (max([Value]) For [Item] in (' + Replace(@SQL,' as Mob','') + ')) p' 

Exec(@SQL); 

返回

enter image description here

編輯

更新於2014年... CONCAT()和值

編輯2:

鑄造nvarchar(50)的另一種選擇是,可以使用format()。例如:

   Values (concat(''Mob_'',A.Date),Format(A.Mob,''0'')) 
        ,(concat('''',A.Date) ,Format(cast(A.Value as decimal(18,2)),''#,##0.00'')) 
      ) B (Item,Value) 
+0

所以我的表被稱爲「特質」,所以我需要用特質替換YourTable? – proctor

+0

@proctor Yup。這應該做的伎倆 –

+0

@proctor只是要清楚,你使用上面列出的代碼?即不是以前的版本 –