Вы можете использовать метод MAX
, чтобы получить необходимые столбцы:
SELECT
MAX(CASE WHEN q.RowNumber = 1 THEN q.ReadTime ELSE NULL END) AS ReadTime
, MAX(CASE WHEN q.RowNumber = 1 THEN q.Location ELSE NULL END) AS Location
, MAX(CASE WHEN q.RowNumber = 1 THEN q.Trailer ELSE NULL END) AS Trailer
, MAX(CASE WHEN q.RowNumber = 1 THEN q.ContainerNumber ELSE NULL END) AS ContainerNumber
, MAX(CASE WHEN q.RowNumber = 2 THEN q.ReadTime ELSE NULL END) AS ReadTime
, MAX(CASE WHEN q.RowNumber = 2 THEN q.Location ELSE NULL END) AS Location
, MAX(CASE WHEN q.RowNumber = 2 THEN q.Trailer ELSE NULL END) AS Trailer
, MAX(CASE WHEN q.RowNumber = 2 THEN q.ContainerNumber ELSE NULL END) AS ContainerNumber
, MAX(CASE WHEN q.RowNumber = 3 THEN q.ReadTime ELSE NULL END) AS ReadTime
, MAX(CASE WHEN q.RowNumber = 3 THEN q.Location ELSE NULL END) AS Location
, MAX(CASE WHEN q.RowNumber = 3 THEN q.Trailer ELSE NULL END) AS Trailer
, MAX(CASE WHEN q.RowNumber = 3 THEN q.ContainerNumber ELSE NULL END) AS ContainerNumber
FROM
(
SELECT
*
, ROW_NUMBER() OVER(PARTITION BY T.Trailer ORDER BY T.Trailer) AS RowNumber
FROM @Table AS T
)AS q
Позвольте мне показать пример:
DECLARE @Table TABLE
(
ReadTime DATETIME,
[Location] VARCHAR(50),
Trailer INT,
ContainerNumber VARCHAR(50)
)
INSERT INTO @Table
(
ReadTime,
Location,
Trailer,
ContainerNumber
)
VALUES
( '2019-02-23 12:22:35.490', 'CUSTOM', 1, 'ZIMU1' )
, ( '2019-02-24 12:22:35.490', 'ZERO', 1, 'ZIMU2' )
, ( '2019-02-25 12:22:35.490', 'CFS', 1, 'ZIMU3')
И использовать приведенный выше запрос, чтобы получить желаемый результат: