Sql server 如何在SQL Server中将两列显示为行?
在SQL Server中将两列转换为行 通过简单交叉应用Sql server 如何在SQL Server中将两列显示为行?,sql-server,Sql Server,在SQL Server中将两列转换为行 通过简单交叉应用 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')
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)
简单应该做的事情:
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
您可以
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
欢迎来到stackoverflow。请阅读。只需使用Pivot将行转换为列即可。这可能是我的荣幸的副本!如果答案有帮助,请随意投票/接受:)这是表示感谢的最佳方式:)