我有一张包含日期和时间列的表格。我需要获得唯一ID的最小日期和时间(col c)以及最大日期和时间(col D)。
E.g
A B C D
1 12/10/2012 8.00 11.00
1 2/10/2013 10.00 12.00
2 1/10/2013 1.00 2.00
2 9/10/2012 6.00 7.00
结果
1 12/10/2012 8.00 2/10/2013 12.00
2 9/10/2012 6.00 1/10/2013 2.00
答案 0 :(得分:3)
WITH CTE AS
(
SELECT A, MIN(B) as MinB, MAX(B) as MaxB
FROM TableName
GROUP BY A
)
SELECT C.A, C.MinB, tMin.C as MinC, C.MaxB, tMax.D as MaxD
FROM CTE C
LEFT JOIN TableName tMin on tMin.A = C.A AND tMin.B = c.MinB
LEFT JOIN TableName tMax on tMax.A = C.A AND tMax.B = c.MaxB