我有一个表结构和样本数据,如下所示:
+----+-----------+------+-------+---------+
| 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月(2012年 - 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 |
+----+-----------+------+-------+---------+
...并获得平均销售价值?有任何想法吗? TIA !!!
答案 0 :(得分:3)
最好的办法是重新组织表格以包含正确的日期。如果需要,您可以将这些列保留在那里以用于特定目的,但是具有适当的日期将允许您使用基于您现在需要做的事情的强大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
那是什么?你想要完整的月份名称? BAM!
select date_format(columnDate, '%M') from .... // output: August