如何在SQL Server中将两列显示为行?

时间:2016-06-27 12:21:34

标签: sql-server

将两列转换为SQL Server中的行

enter image description here

3 个答案:

答案 0 :(得分:0)

通过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')

脚本:

 select COL AS [Instal OR Uninstall],VAL AS [Date] from @Table1
        CROSS APPLY
    (VALUES 
    ('installdate',installdate),
    ('uninstalldate',installdate))
    CS(COL,VAL)

答案 1 :(得分:0)

简单UNPIVOT应该做的事情:

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

输出:

DATES           VALUES
InstallDate     2016-06-15
UnInstallDate   2016-06-18
InstallDate     2016-06-20
UnInstallDate   2016-06-25

答案 2 :(得分:0)

您可以将UNPIVOT列添加到行中:

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

这会产生以下行:

ActivityType              ActivityDate
------------------------- ------------
InstallDate               2016-06-15
UnInstallDate             2016-06-18
InstallDate               2016-06-20
UnInstallDate             2016-06-25