MySQL - Max() return wrong result

佐手、 提交于 2019-12-06 17:26:27
ceejayoz

As you can see, the maximum volume is VERY different from the 'real' value of the volume column?!?

This is because MySQL rather bizarrely doesn't GROUP things in a sensical way.

Selecting MAX(column) will get you the maximum value for that column, but selecting other columns (or column itself) will not necessarily select the entire row that the found MAX() value is in. You essentially get an arbitrary (and usually useless) row back.

Here's a thread with some workarounds using subqueries: How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?

czep

This is a subset of the "greatest n per group" problem. (There is a tag with that name but I am a new user so I can't retag).

This is usually best handled with an analytic function, but can also be written with a join to a sub-query using the same table. In the sub-query you identify the max value, then join to the original table on the keys to find the row that matches the max.

Assuming that {dateofclose, symbol, market} is the grain at which you want the maximum volume, try:

select
    a.*, b.max_volume
from daily a
join
(
    select
        dateofclose, symbol, market, max(volume) as max_volume
    from daily
    group by
        dateofclose, symbol, market
) b
on
    a.dateofclose = b.dateofclose
    and a.symbol = b.symbol
    and a.market = b.market

Also see this post for reference.

Did you try adjusting your query to include Symbol in the grouping?

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