Это один из возможных подходов, если ваш заказ убывает на [Date]
столбец:
Ввод:
CREATE TABLE #Table (
[Date] datetime,
A int,
B int,
C int,
D int
)
INSERT INTO #Table
([Date], A, B, C, D)
VALUES
('2010-11-16T10:02:00.000', 10 , NULL, NULL, NULL),
('2010-09-21T00:00:00.000', 86 , 14 , NULL, 17 ),
('2010-07-27T00:00:00.000', 125 , 12 , NULL, 11 ),
('2010-05-29T15:24:00.000', NULL, NULL, 1250, NULL)
Заявление:
SELECT
[Date] = (SELECT TOP 1 [Date] FROM #Table WHERE [Date] IS NOT NULL ORDER BY [Date] DESC),
[A] = (SELECT TOP 1 [A] FROM #Table WHERE [A] IS NOT NULL ORDER BY [Date] DESC),
[B] = (SELECT TOP 1 [B] FROM #Table WHERE [B] IS NOT NULL ORDER BY [Date] DESC),
[C] = (SELECT TOP 1 [C] FROM #Table WHERE [C] IS NOT NULL ORDER BY [Date] DESC),
[D] = (SELECT TOP 1 [D] FROM #Table WHERE [D] IS NOT NULL ORDER BY [Date] DESC)
Выход:
Date A B C D
2010-11-16 10:02:00.000 10 14 1250 17
Обновление - еще один возможный подход с использованием агрегатных функций:
;WITH DatesCTE AS (
SELECT
[Date] = MAX([Date]),
[DateA] = MAX(CASE WHEN A IS NOT NULL THEN [Date] END),
[DateB] = MAX(CASE WHEN B IS NOT NULL THEN [Date] END),
[DateC] = MAX(CASE WHEN C IS NOT NULL THEN [Date] END),
[DateD] = MAX(CASE WHEN D IS NOT NULL THEN [Date] END)
FROM #Table
)
SELECT
d.[Date],
A = MAX(CASE WHEN t.[Date] = d.[DateA] THEN A END),
B = MAX(CASE WHEN t.[Date] = d.[DateB] THEN B END),
C = MAX(CASE WHEN t.[Date] = d.[DateC] THEN C END),
D = MAX(CASE WHEN t.[Date] = d.[DateD] THEN D END)
FROM DatesCTE d
CROSS APPLY #Table t
GROUP BY d.[Date]