Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unpivot columns using CROSS APPLY in SQL Server 2012

I want to use CROSS APPLY to UNPIVOT multiple columns.

The columns CGL, CPL, EO should become Coverage Type, the values for CGL, CPL, EO should go in column Premium, and values for CGLTria,CPLTria,EOTria should go in column Tria Premium

declare @TestDate table  ( 
                            QuoteGUID varchar(8000), 
                            CGL money, 
                            CGLTria money, 
                            CPL money,
                            CPLTria money,
                            EO money,
                            EOTria money
                            )

INSERT INTO @TestDate (QuoteGUID, CGL, CGLTria, CPL, CPLTria, EO, EOTria)
VALUES ('2D62B895-92B7-4A76-86AF-00138C5C8540', 2000, 160, 674, 54, 341, 0),
       ('BE7F9483-174F-4238-8931-00D09F99F398', 0, 0, 3238, 259, 0, 0),
       ('BECFB9D8-D668-4C06-9971-0108A15E1EC2', 0, 0, 0, 0, 0, 0)

SELECT * FROM @TestDate

Output:

enter image description here

The result should be like that :

enter image description here

like image 716
Serdia Avatar asked Feb 07 '18 00:02

Serdia


People also ask

How do I Unpivot multiple columns?

Select the columns you do want to unpivot. To select more than one column contiguously or discontiguously, press Shift+Click or CTRL+Click on each subsequent column. Select Transform > Unpivot Only Selected Columns.

How do I Unpivot data in SQL Server?

UNPIVOT carries out the opposite operation to PIVOT by rotating columns of a table-valued expression into column values. The syntax for PIVOT provides is simpler and more readable than the syntax that may otherwise be specified in a complex series of SELECT...CASE statements.


1 Answers

One quick and easy way is with VALUES

Example

select A.QuoteGUID
      ,B.*
 From  @TestDate A
 Cross Apply ( values ('CGL',CGL,CGLTria)
                     ,('CPL',CPL,CPLTria)
                     ,('EO',EO,EOTria)
             ) B (CoverageType,Premium,TiraPremium)

Returns

enter image description here

like image 60
John Cappelletti Avatar answered Oct 04 '22 18:10

John Cappelletti