简体   繁体   中英

SQL Server : getting multiple min/max values from one query

I have data similar to the following in SQL Server. I would like to query the single table for the category, min value from StartDate and max value from EndDate . Hopefully the following mock up of the data will help explain - thanks

DATA:

  Category  StartDate   EndDate
  -------------------------------
       A    1/1/2018    1/11/2018
       A    1/3/2018    1/13/2018
       B    1/1/2018    1/11/2018
       B    1/9/2018    1/19/2018
       A    1/5/2018    1/15/2018
       C    1/4/2018    1/14/2018
       A    1/1/2018    1/11/2018
       C    1/7/2018    1/17/2018

Desired result of query:

  Category  StartDate   EndDate
  --------------------------------
       A    1/1/2018    1/15/2018
       B    1/1/2018    1/19/2018
       C    1/4/2018    1/17/2018

What's wrong with GROUP BY and MIN() & MAX() ?

select Category, min(startdate) startdate, max(enddate) enddate
from table t
group by Category;

Use group by

select category, min(startDate), max(endDate)
from my_table  
group by category

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