-4

Convert two column to rows in SQL Server

enter image description here

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Rohit
  • 1
  • 1

3 Answers3

0

by Simple Cross Apply

DECLARE @Table1  TABLE 
    (ID int,installdate varchar(20),uninstalldate varchar(20))
;

INSERT INTO @Table1
    (ID,installdate,uninstalldate)
VALUES
    (1,'15/06/2016','18/06/2016'),
    (2,'20/06/2016','25/06/2016')

Script :

 select COL AS [Instal OR Uninstall],VAL AS [Date] from @Table1
        CROSS APPLY
    (VALUES 
    ('installdate',installdate),
    ('uninstalldate',installdate))
    CS(COL,VAL)
mohan111
  • 8,633
  • 4
  • 28
  • 55
0

Simple UNPIVOT should do thing:

SELECT  [DATES], 
        [VALUES]
FROM MyTable
UNPIVOT (
    [VALUES] FOR [DATES] IN (InstallDate,UnInstallDate)
) as unpvt

Output:

DATES           VALUES
InstallDate     2016-06-15
UnInstallDate   2016-06-18
InstallDate     2016-06-20
UnInstallDate   2016-06-25
gofr1
  • 15,741
  • 11
  • 42
  • 52
  • My pleasure! If answer(s) were helpful feel free to upvote/accept them :) That is the best way to say *thank you* here :) – gofr1 Jun 28 '16 at 11:20
0

You can UNPIVOT the columns into rows:

DECLARE @Data TABLE (
    Id INT,
    InstallDate DATE,
    UnInstallDate DATE
)
INSERT @Data VALUES (1,'6/15/2016', '6/18/2016'),(2,'6/20/2016', '6/25/2016')

SELECT
    ActivityType,
    ActivityDate
FROM @Data 
    UNPIVOT (ActivityDate FOR ActivityType IN (InstallDate, UnInstallDate)) T

This produces the following rows:

ActivityType              ActivityDate
------------------------- ------------
InstallDate               2016-06-15
UnInstallDate             2016-06-18
InstallDate               2016-06-20
UnInstallDate             2016-06-25
Jason W
  • 13,026
  • 3
  • 31
  • 62