【问题标题】:How to select past six months sales value?如何选择过去六个月的销售价值?
【发布时间】:2012-08-13 08:25:26
【问题描述】:

我有这样的表结构和示例数据:

+----+-----------+------+-------+---------+
| id | item_code | year | month | sales   |
+----+-----------+------+-------+---------+
| 1  |   12341   | 2011 |   10  | 1000000 |
+----+-----------+------+-------+---------+
| 2  |   12342   | 2011 |   11  | 2000000 |
+----+-----------+------+-------+---------+
| 3  |   12343   | 2011 |   12  | 3000000 |
+----+-----------+------+-------+---------+
| 4  |   12344   | 2012 |   01  | 4000000 |
+----+-----------+------+-------+---------+
| 5  |   12345   | 2012 |   02  | 5000000 |
+----+-----------+------+-------+---------+
| 6  |   12346   | 2012 |   03  | 6000000 |
+----+-----------+------+-------+---------+
| 7  |   12347   | 2012 |   04  | 6000000 |
+----+-----------+------+-------+---------+

现在我的问题是,例如当前月份是 2012 年 8 月(04 - 2012),我们如何选择过去六个月的数据是:

+----+-----------+------+-------+---------+
| id | item_code | year | month | sales   |
+----+-----------+------+-------+---------+
| 1  |   12341   | 2011 |   10  | 1000000 |
+----+-----------+------+-------+---------+
| 2  |   12342   | 2011 |   11  | 2000000 |
+----+-----------+------+-------+---------+
| 3  |   12343   | 2011 |   12  | 3000000 |
+----+-----------+------+-------+---------+
| 4  |   12344   | 2012 |   01  | 4000000 |
+----+-----------+------+-------+---------+
| 5  |   12345   | 2012 |   02  | 5000000 |
+----+-----------+------+-------+---------+
| 6  |   12346   | 2012 |   03  | 6000000 |
+----+-----------+------+-------+---------+

...并获得平均销售价值?有任何想法吗?蒂亚!!!

【问题讨论】:

    标签: php mysql average


    【解决方案1】:

    最好的办法是重新组织表格以包含正确的日期。如果需要,您可以将这些列保留在其中以用于特定目的,但是拥有适当的日期将使您能够使用强大的 SQL 函数,这些函数完全基于您现在需要做的事情。

    例如,您将能够执行以下操作:

    select someData from yourTable where columnDate>=date_sub(now(), interval 6 month);
    

    正如 eggyal 正确提到的,您将能够轻松获得很多这样的聚合函数:

    select avg(sales) from ...
    

    这将恢复您放入 where 子句的条件(例如过去 6 个月)的平均销售额。

    如果您甚至不保留当前的年/月列,您可以通过以下方式获得 info out of a date column

    select date_format(columnDate, '%Y') from .... // output: 2012
    

    那是什么?你想要现在的月份吗?

    select date_format(columnDate, '%m') from .... // output: 08
    

    那是什么?你想要完整的月份名称吗?砰!

    select date_format(columnDate, '%M') from .... // output: August
    

    【讨论】:

    • 然后要得到平均值,只需要SELECT AVG(sales) FROM ...
    • 感谢您的想法,但 where 子句似乎不起作用,它说:#1064 - 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以获取在 '6 MONTH 附近使用的正确语法)
    • @Mico 你是对的。我错过了查询中的interval。我已根据需要更新了我的答案。 +1 调用我的错误 :)
    猜你喜欢
    • 1970-01-01
    • 2015-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多