mysql 从选择中选择

2022-01-23 00:00:00 select subquery mysql

我有这个问题:

    SELECT DATE( a.created_at ) AS order_date, count( * ) as cnt_order
    FROM `sales_order_item` AS a
    WHERE MONTH( a.created_at ) = MONTH( now())-1
    GROUP BY order_date

这将返回类似这样的结果(仅快照,否则将每 31 天返回一次):

which will return result something like this (snapshot only otherwise will return per 31 days):

order_date  cnt_order 
2012-08-29  580
2012-08-30  839
2012-08-31  1075

我的完整查询是根据上述选择进行选择的:

and my full query is selecting based on above selection:

SELECT order_date
    , MAX(cnt_order) AS highest_order
FROM (
        SELECT DATE (a.created_at) AS order_date
            , count(*) AS cnt_order
        FROM `sales_order_item` AS a
        WHERE MONTH(a.created_at) = MONTH(now()) - 1
        GROUP BY order_date
    ) AS tmax

但结果是:

order_date  highest_order
2012-08-01  1075

哪个日期有误,总是选择它假设为 2012 年 8 月 31 日的第一行日期.也许这是一个我不知道的简单错误.那么如何让日期正确指向 2012-08-31?任何帮助都会很棒.

Which has the date wrong and always pick the first row of date where it suppose 2012-08-31. Maybe this is a simple error that I dont know. So how to get the date right point to 2012-08-31? Any help would be great.

推荐答案

可以尝试排序子查询结果集;类似:

You could try ordering the sub query result set; something like:

SELECT
    DATE (a.created_at) AS order_date,
    COUNT(*) AS cnt_order
FROM
    `sales_order_item` AS a
WHERE
    MONTH(a.created_at) = MONTH(now()) - 1
GROUP BY
    order_date
ORDER BY
    cnt_order DESC

相关文章