1

Hi I have my data in a table like this:

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

I need it changed from Long to wide format using the PIVOT function

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

Any help would be greatly appreciated

1
  • I also have multiple Dates (hundreds.) Commented Jan 25, 2017 at 22:40

1 Answer 1

1

Here is a Dynamic Pivot for multiple columns

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);

Returns

enter image description here

EDIT

Updated for 2014 ... Concat() and Values

EDIT 2:

Another option to casting a nvarchar(50), you could use format(). For example:

             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)
Sign up to request clarification or add additional context in comments.

16 Comments

So my table is called "Trait" so I need to replace YourTable with trait?
@proctor Just to be clear, are you using the code listed above? ie not a previous version
Yes Ive copied your code - I'm running SQL Server 2014
@proctor you tagged 2008. I would have used concat() and values rather than Union All. Do you want the change?
Yeah sorry John - if you could please
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.