をチェックこれで遊んでみてください:あなたは `pivot`を探している
DECLARE @DataSource TABLE
(
[ID] INT
,[Height] INT
,[Color] VARCHAR(12)
,[Type] VARCHAR(12)
,[TimeStamp] DATETIME2
);
INSERT INTO @DataSource ([ID], [Height], [Color], [Type], [TimeStamp])
VALUES ('1', '6', 'Green', 'Plant', '2017-09-23')
,('1', '24', 'Red', 'Tree', ' 2017-09-15')
,('1', '33', 'Pink', 'Shrub', '2016-05-14')
,('1', '33', 'Pink', 'Shrub 1', '2016-05-13')
,('1', '33', 'Pink', 'Shrub 2', '2016-05-12')
,('1', '33', 'Pink', 'Shrub 3', '2016-05-11')
,('2', '12', 'Blue', 'Car', ' 2017-03-21')
,('2', '88', 'Pink', 'Truck', '2017-11-22')
,('3', '12', 'test', 'test 2', '2017-11-22');
SELECT [ID]
,MAX(CASE WHEN [RowID] = 1 THEN [Height] ELSE NULL END) AS [Height1]
,MAX(CASE WHEN [RowID] = 1 THEN [Color] ELSE NULL END) AS [Color1]
,MAX(CASE WHEN [RowID] = 1 THEN [Type] ELSE NULL END) AS [Type1]
,MAX(CASE WHEN [RowID] = 2 THEN [Height] ELSE NULL END) AS [Height2]
,MAX(CASE WHEN [RowID] = 2 THEN [Color] ELSE NULL END) AS [Color2]
,MAX(CASE WHEN [RowID] = 2 THEN [Type] ELSE NULL END) AS [Type2]
FROM
(
SELECT TOP (4) WITH TIES *
,ROW_NUMBER() OVER (PARTITION BY [ID] ORDER BY [TimeStamp] DESC) AS [RowID]
FROM @DataSource
ORDER BY [RowID]
) DS
GROUP BY [ID];
。 'color = 'pink'(ID = 1の場合)はどうなりましたか? – HoneyBadger
最初のIDは3行分ですか?それは 'Height3'などでしょうか? – gofr1
各IDに最後の行が2つだけ必要ですか? – gofr1