SQL Server 中的复杂数据透视表
Posted
技术标签:
【中文标题】SQL Server 中的复杂数据透视表【英文标题】:Complex Pivot table in SQL Server 【发布时间】:2021-07-14 17:53:20 【问题描述】:我有一些看起来像这样的数据:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tblMyLog]
(
[Pkid] [bigint] IDENTITY(1,1) NOT NULL,
[JobId] [int] NOT NULL,
[log_recorded] [datetime] NOT NULL,
[status] [nvarchar](max) NULL
)
GO
SET IDENTITY_INSERT [dbo].[tblMyLog] ON
GO
INSERT [dbo].[tblMyLog] ([Pkid], [JobId], [log_recorded], [status])
VALUES (1, 1, CAST(N'2021-06-29T15:35:09.917' AS DateTime), N'Started')
GO
INSERT [dbo].[tblMyLog] ([Pkid], [JobId], [log_recorded], [status])
VALUES (2, 1, CAST(N'2021-06-29T15:36:08.810' AS DateTime), N'Ended')
GO
INSERT [dbo].[tblMyLog] ([Pkid], [JobId], [log_recorded], [status])
VALUES (3, 2, CAST(N'2021-06-29T15:33:41.133' AS DateTime), N'Started')
GO
INSERT [dbo].[tblMyLog] ([Pkid], [JobId], [log_recorded], [status])
VALUES (4, 2, CAST(N'2021-06-29T15:35:09.917' AS DateTime), N'Ended')
GO
我想获得这样的格式,所以我从另一个表中对 tblMyLog 进行了一些连接:
JobId StartTime EndTime
------------------------------------------------------
1 2021-06-29 15:35:09.917 2021-06-29 15:36:08.810
2 2021-06-29 15:33:41.133 2021-06-29 15:35:09.917
但我无法弄清楚执行此操作的数据透视表语法。
【问题讨论】:
docs.microsoft.com/en-us/sql/relational-databases/… 【参考方案1】:假设JobID
可以有多个开始/结束时间,我们可以使用窗口函数sum() over()
创建一个临时组Grp
示例
Select JobID
,StartTime = min( case when status='Started' then log_recorded end)
,EndTime = max( case when status='Ended' then log_recorded end)
From (
Select *
,Grp = sum( case when status='Started' then 1 end) over ( partition by JobID order by log_recorded)
From [tblMyLog]
) A
Group By JobID,Grp
结果
JobID StartTime EndTime
1 2021-06-29 15:35:09.917 2021-06-29 15:36:08.810
2 2021-06-29 15:33:41.133 2021-06-29 15:35:09.917
【讨论】:
以上是关于SQL Server 中的复杂数据透视表的主要内容,如果未能解决你的问题,请参考以下文章