0

I have a query that when executed gives me the result like this

speciaid         | title     | date
one              | xxx       | 2013-10-03 02:13:54
one              | xxx       | 2013-10-03 03:13:54
two              | yyy       | 2013-10-02 02:13:54

Now if I add GROUP BY specialid, it gets grouped but the date i get is the old date and not the new date for the 'date' column like this

speciaid         | title     | date
one              | xxx       | 2013-10-03 02:13:54      // old date selected for entry one
two              | yyy       | 2013-10-02 02:13:54

and I want it like this

speciaid         | title     | date
one              | xxx       | 2013-10-03 03:13:54   // new date for entry one needed
two              | yyy       | 2013-10-02 02:13:54

I have tried many group by's - I get the same result. I would appreciate it very much if someone help with the group by statement for query.

4

3 回答 3

0
select speciaid, title , date
from
(select * from table_name order by date desc) d
group by title
于 2013-10-04T05:31:31.207 回答
0

您正在寻找每组最大 n 的解决方案。

通常以这种方式解决(假设您的结果是表格,由于问题中缺乏信息)。

选项1:

SELECT * FROM t JOIN (
  SELECT title, max(`date`) `date` FROM t
  GROUP BY title
) s ON t.title = s.title AND t.`date` = s.`date`

选项 2:

SELECT t1.* FROM t t1
LEFT JOIN t t2
ON t1.title = t2.title AND t1.`date` < t2.`date`
WHERE t2.`date` IS NULL

工作小提琴:http ://sqlfiddle.com/#!2/76f2d3/1

于 2013-10-04T05:19:10.747 回答
0

如果要从分组列中获取第一个/最后一个日期,则需要使用 max() 或 min() 分组函数。

SELECT speciaid, title, MAX(`date`) FROM table GROUP BY title;
于 2013-10-04T05:20:48.187 回答