MySQL - using GROUP BY and DESC

三世轮回 提交于 2019-11-29 12:15:52

问题


In my SQL query I am selecting data with GROUP BY and ORDER BY clauses. The table has the same numbers across multiple rows with different times in each row. So I think I want to apply a GROUP BY clause.

However in the results return the oldest time with the number, but I need the most recent time.

SELECT * FROM TABLE GROUP BY (numbers) ORDER BY time DESC

The query appears as if it should first apply GROUP BY and then ORDER BY... but the results do not appear to work this way.

Is there any way to fix this?


回答1:


work-around is to re-write the query as:

SELECT * FROM (SELECT * FROM table ORDER BY time DESC) AS t GROUP BY numbers;



回答2:


SELECT * 
FROM table t
WHERE time = (
    SELECT max(time)
    FROM table
    WHERE t.numbers = numbers
)



回答3:


SELECT * FROM table
    WHERE time IN (
        SELECT MAX(time)
            FROM table
            GROUP BY numbers
    )



回答4:


According to the manual you can add desc to the group by list: Example:
group by item1, item2 desc, item3

with or without rollup.

I've tried this and it works in Ubuntu version 5.5.58. The reference page is: https://dev.mysql.com/doc/refman/5.7/en/group-by-modifiers.html




回答5:


SELECT * FROM TABLE GROUP BY numbers DESC;

This will give you last record from group.

Thanks



来源:https://stackoverflow.com/questions/7306082/mysql-using-group-by-and-desc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!