简体   繁体   中英

Looking for a solution to a SQL GROUP BY … WHERE MIN date

EDIT: The following question is angled at both MS-SQL and MySQL.

I've been pondering over this for a good 7 hours now. I've seen many stack overflow answers that are similar, but none that i've properly understood or worked out how to implement.

I am looking to SELECT id, title, etc etc FROM a table, WHERE the date is the next available date AFTER NOW(). The catch is, it needs to be GROUPED BY one particular column.

Here is the table:

==================================

id    |    name    |    date_start    |    sequence_id
--------------------------------------------------------
  1    |   Foo1     |     20150520     |       70
  2    |   Foo2     |     20150521     |       70
  3    |   Foo3     |     20150522     |       70
  4    |   Foo4     |     20150523     |       70
  5    |   FooX     |     20150524     |       70
  6    |   FooY     |     20150525     |       70
  7    |   Bar      |     20150821     |       61
  8    |   BarN     |     20151110     |       43
  9    |   BarZ     |     20151104     |       43

And here is what I would like to see:

==================================

id    |    name    |    date_start    |    sequence_id
--------------------------------------------------------
  1    |   Foo1     |     20150520     |       70
  7    |   Bar      |     20150821     |       61
  9    |   BarZ     |     20151104     |       43

The results are filtered by MIN(date_start) > NOW() AND GROUPED BY sequence_id.

I'm not entirely sure this can be achieved with a GROUP BY as the rest of the columns would need to be contained within an aggregate function which I don't think will work.

Does anyone have an answer for this dilemma?

Many Thanks!

Simon

Just use a join and aggregation in a subquery:

select t.*
from table t join
     (select sequence_id, min(date_start) as minds
      from table t
      group by sequence_id
     ) tt
     on tt.sequence_id = t.sequence_id and t.date_start = tt.minds;

This is standard SQL, so it should run in any database.

http://sqlfiddle.com/#!9/d8576/4

SELECT *
FROM table1 as t1
LEFT JOIN
  (SELECT * 
   FROM table1
   WHERE date_start>NOW()
  ) as t2
ON t1.sequence_id = t2.sequence_id and t1.date_start>t2.date_start
WHERE t1.date_start>NOW() and t2.date_start IS NULL
GROUP BY t1.sequence_id

MSSQL fiddle

SELECT *
FROM table1 as t1
LEFT JOIN
  (SELECT * 
   FROM table1
   WHERE date_start>GetDate()
  ) as t2
ON t1.sequence_id = t2.sequence_id and t1.date_start>t2.date_start
WHERE t1.date_start>GetDate() and t2.date_start IS NULL

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