sql-server - 在一段时间内透视/转换 SQL 结果集
问题描述
请运行以下代码以查看结果集。
IF OBJECT_ID('tempdb..#temptable') IS NOT NULL DROP TABLE #temptable
CREATE TABLE #temptable ( [VehicleKey] int, [RegistrationKey] int, [RegisteredOperatorKey] int, [StartDate] date )
INSERT INTO #temptable
VALUES
( 700090, 550983, 207287, N'2018-07-31T00:00:00' ),
( 700090, 1513637, 276879, N'2018-12-31T00:00:00' ),
( 700090, 1513637, 341604, N'2019-02-28T00:00:00' )
SELECT * FROM #temptable
如何将结果集转换为如下所示?
请注意,钥匙始终是 VehicleKey。请注意 StartDate 记录如何随时间变化的车辆。
解决方案
这将为您提供所需的输出。SELECT * FROM #temptable
用下面的代码替换语句
;WITH tt AS (
SELECT *,
ROW_NUMBER() OVER (partition by VehicleKey ORDER BY StartDate) AS Seq
FROM #tempTable
)
SELECT t1.VehicleKey,
t1.RegistrationKey As OldRegistrationKey,
t2.RegistrationKey As NewRegistrationKey,
t1.RegisteredOperatorKey AS OldRegisteredOperatorKey,
t2.RegisteredOperatorKey AS NewRegisteredOperatorKey,
t1.StartDate as OldStartDate,
t2.StartDate as NewStartDate
FROM tt t1
INNER JOIN tt t2
ON t1.VehicleKey = t2.VehicleKey
AND t1.Seq = t2.Seq - 1
推荐阅读
- javascript - 我正在尝试获得特定时期的总利息
- javascript - 无法访问捆绑到同一个 Browserify 包中的模块之间的功能?
- java - Beam Java SDK 2.4/2.5 PAssert 与 CoGroupByKey
- angular - 在 Firebase 上部署 Angular 6 Universal
- python - 根据另一列中的分类变量为公共键添加字典值
- matlab - 使用matlab查找与在最小值附近振荡的值相对应的索引
- c++ - OpenGL 我的纹理显示为单一颜色?
- amazon-web-services - RPM 仅安装在 AWS ec2 redhat 实例上
- ios - 如何在 Swift 中设置 MediaPlayer 播放速率?
- c++ - 打印出用户从未输入的数字的数组副本