开发者

MySQL - using GROUP BY and DESC

开发者 https://www.devze.com 2023-04-03 04:49 出处:网络
In my SQL query I am selecting开发者_如何学JAVA 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 appl

In my SQL query I am selecting开发者_如何学JAVA 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?


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


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

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


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


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


SELECT * FROM TABLE GROUP BY numbers DESC;

This will give you last record from group.

Thanks

0

精彩评论

暂无评论...
验证码 换一张
取 消