将行转移到列而不会发生混乱

时间:2017-05-19 10:30:14

标签: sql pivot

我想根据RuleID和Dname将行转换为列。以下是示例数据。请帮助我实现它

CREATE TABLE [dbo].[Table1](
[RuleID] [nvarchar](10) NULL,
[DateTime1] [datetime] NULL,
[DName] [nvarchar](30) NULL
) ON [PRIMARY]

INSERT [dbo].Table1 ([RuleID], [DateTime1], [DName]) VALUES (N'DBRS', CAST(N'2017-03-28T12:22:04.000' AS DateTime), N'DB1')
INSERT [dbo].Table1 ([RuleID], [DateTime1], [DName]) VALUES (N'DBRK', CAST(N'2017-03-28T12:22:04.260' AS DateTime), N'DB1')
INSERT [dbo].Table1 ([RuleID], [DateTime1], [DName]) VALUES (N'DBRE', CAST(N'2017-03-28T12:22:09.000' AS DateTime), N'DB1')
INSERT [dbo].Table1 ([RuleID], [DateTime1], [DName]) VALUES (N'DBRK', CAST(N'2017-04-04T08:33:15.870' AS DateTime), N'DB2')
INSERT [dbo].Table1 ([RuleID], [DateTime1], [DName]) VALUES (N'DBRE', CAST(N'2017-04-04T08:33:31.000' AS DateTime), N'DB2')
INSERT [dbo].Table1 ([RuleID], [DateTime1], [DName]) VALUES (N'DBRK', CAST(N'2017-04-04T09:14:30.503' AS DateTime), N'DB2')
INSERT [dbo].Table1 ([RuleID], [DateTime1], [DName]) VALUES (N'DBRS', CAST(N'2017-04-04T09:14:31.000' AS DateTime), N'DB2')
INSERT [dbo].Table1 ([RuleID], [DateTime1], [DName]) VALUES (N'DBRE', CAST(N'2017-04-04T09:44:33.000' AS DateTime), N'DB2')

期望的输出:

SELECT 'DB1' As DName,'2017-03-28 12:22:04.260'AS BRKIndicated ,'2017-03-28 12:22:04.000' As BRKStart,'2017-03-28 12:22:09.000' AS BRKEnd
UNION
SELECT 'DB2'As DName,'2017-04-04 08:33:15.870'AS BRKIndicated,NULL As BRKStart,'2017-04-04 08:33:31.000'AS BRKEnd
UNION
SELECT 'DB2'As DName,'2017-04-04 09:14:30.503'AS BRKIndicated,'2017-04-04 09:14:31.000' As BRKStart,'2017-04-04 09:44:33.000'AS BRKEnd

2 个答案:

答案 0 :(得分:0)

使用PIVOT表:

SELECT *
FROM 
(
   SELECT * 
   FROM Table1
) A 
PIVOT
(
  MAX(DateTime1) FOR RuleID IN ([DBRS],[DBRK],[DBRE])
)pvt 

答案 1 :(得分:0)

使用自我加入

select D1.DName, D1.DateTime1 as DBRS, D2.DateTime1 as DBRK, D3.DateTime1 as DBRE
from Table1 D1
inner join Table1 D2
  on D1.DName = D2.DName
  and D2.RuleID = 'DBRK'
inner join Table1 D3
  on D1.DName = D3.DName
  and D3.RuleID = 'DBRE'
where D1.RuleID = 'DBRS'

如果可能缺少其中一个值,请改用<{1}}