简体   繁体   中英

Select earliest and latest dates from two rows and return a single row?

Let's say I have this result set:

Title                                CourseEventKey CourseKey   StartDate               EndDate
------------------------------------ -------------- ----------- ----------------------- -----------------------
Branch Summit 2012 - Power of Team   32             657         2012-05-22 08:00:00.000 2012-05-22 17:00:00.000
Branch Summit 2012 - Power of Team   32             657         2012-05-23 08:00:00.000 2012-05-23 17:00:00.000

As you can see, these rows have duplicate values in every column except for StartDate and EndDate .

I need this result set to contain only distinct values in CourseEventKey by calculating the earliest StartDate and latest EndDate and selecting the resulting values into their corresponding columns.

How can I do this?

Thanks in advance.

This is very easily done with a group by.

 SELECT name, MAX(enddate), MIN(startdate) FROM MyTable
 GROUP BY name;
 SELECT Title, CourseEventKey, CourseKey, MIN( StartDate), MAX(StartDate)
 FROM Table
 GROUP BY Title, CourseEventKey, CourseKey

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