简体   繁体   中英

Getting Min and Max Value of a column and other column values

I have a table with columns of date and time. I need to get the minimum date and its time (col c) and Maximum date and its time( col D) for a unique id.

Eg

     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

RESULT

     1  12/10/2012   8.00    2/10/2013  12.00
     2  9/10/2012    6.00    1/10/2013   2.00
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM