寻找SQL GROUP BY .... WHERE MIN日期的解决方案

时间:2015-03-24 15:53:23

标签: sql sql-server group-by aggregate-functions

编辑:以下问题与MS-SQL和MySQL有关。

我现在已经好好整理了7个小时了。我已经看到很多类似的堆栈溢出答案,但没有一个我已经正确理解或计算出如何实现。

我期待从表中选择SELECT id,title,e.t.c e.t.c,其中日期是NOW()之后的下一个可用日期。问题是,它需要由一个特定列组成GROUPED。

这是表格:

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

 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

以下是我希望看到的内容:

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

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

结果通过MIN(date_start)>过滤。 NOW()和由sequence_id分组。

我不完全确定使用GROUP BY可以实现这一点,因为其他列需要包含在我认为不会起作用的聚合函数中。

有没有人能解决这个难题?

非常感谢!

西蒙

2 个答案:

答案 0 :(得分:1)

只需在子查询中使用join和聚合:

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;

这是标准SQL,因此它应该在任何数据库中运行。

答案 1 :(得分:0)

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
相关问题