2

Trying to get an Unpivot to apply across a few columns and am struggling to get it to work correctly. Maybe its not the right solution so definitely open to suggestions. Here's an example of my dataset

Sample Data Set In Excel

Sample Wanted Data Set In Excel

Sorry for the links, can't quite stick pics in these posts just yet.

Here's the code that I'm close to, it seems like I'm close...but maybe not.

SELECT 
    RunDate,
    ShipMode,
    Amt
FROM
    (SELECT
         CAST(sh.RunDt as DATE) as RunDt,
         sh.method1, sh.method2, sh.method3,
         sh.method4, sh.method5
     FROM 
         [dbo].sampletable sh
     WHERE 
         RunDt = '2016-10-17') AS P
UNPIVOT (
    RunDate FOR ShipMode IN(method1, method2, method3,method4, method5)
) AS Unpvt

2 Answers 2

3

You just have a couple of names wrong. You can unpivot using the SQL:

SELECT 

RunDt ,ShipMode ,Amt FROM (

 SELECT 
 CAST(sh.RunDt as DATE) as RunDt
,sh.method1 
,sh.method2 
,sh.method3  
,sh.method4 
,sh.method5
FROM [dbo].sampletable  sh
WHERE RunDt = '2018-10-17'

) AS P UNPIVOT ( Amt FOR ShipMode IN(method1, method2, method3,method4, method5) ) as Unpvt
Sign up to request clarification or add additional context in comments.

Comments

1

Rather than UNPIVOT, another option is using a CROSS APPLY. It offers a bit more flexibility

Example

Select A.RunDt
      ,B.*
 From  YourTable A
 Cross Apply ( values ('Method1',Method1)
                     ,('Method2',Method2)
                     ,('Method3',Method3)
                     ,('Method4',Method4)
                     ,('Method5',Method5)
             ) B(Overall,Amt)
 Where RunDt = '2016-10-17'

Comments

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.