mysql 从选择中选择

mysql Select from Select(mysql 从选择中选择)
本文介绍了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

这篇关于mysql 从选择中选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)