从当前周的订单表中提取记录

时间:2012-10-29 02:17:04

标签: php mysql codeigniter datetime

我有一张包含以下信息的表...

Id | orderNumber | orderDate | customerId

orderDate是一个MySQL日期时间字段,当前日,月,年和时间在写入记录时插入到数据库中。

所以我的问题是如何在本周的某一天提取订单清单。我的目标是使用谷歌图表API为“本周的销售”制作一个图表,其中包含:

 var data = google.visualization.arrayToDataTable([
                      ['Day', 'Sales'],
                      ['Mon',  1],
                      ['Tue',  0],
                      ['Wed',  4],
                      ['Thurs',  3],
                      ['Fri',  0],
                    ]);

1 个答案:

答案 0 :(得分:3)

让我们做你想做的事:

SELECT
    WEEKDAY(`datetime_field`) AS `week_day`,
    COUNT(*) AS `sale_count`
FROM `orders`
WHERE YEARWEEK(`datetime_field`) = YEARWEEK(NOW())
GROUP BY `week_day`
ORDER BY `week_day` ASC;

这会返回一组包含week_daysale_count的记录。 Learn more here。如果您使用本地日期时间,请使用NOW();如果您使用GMT,请使用UTC_TIMESTAMP()

请记住,我不知道您的数据库名称或字段'名。你需要填写。

工作示例:

CREATE TABLE `orders` (
  `OrderID` int(11) NOT NULL AUTO_INCREMENT,
  `OrderDate` datetime NOT NULL,
  `OrderValue` decimal(7,2) unsigned NOT NULL,
  PRIMARY KEY (`OrderID`)
);

INSERT INTO `orders` VALUES ('1', '2012-10-29 14:02:19', '100.00');
INSERT INTO `orders` VALUES ('2', '2012-10-30 14:02:19', '123.00');
INSERT INTO `orders` VALUES ('3', '2012-10-31 14:02:19', '103.00');
INSERT INTO `orders` VALUES ('4', '2012-11-01 14:02:19', '232.00');
INSERT INTO `orders` VALUES ('5', '2012-11-02 14:02:19', '321.00');
INSERT INTO `orders` VALUES ('6', '2012-11-03 14:02:19', '154.00');
INSERT INTO `orders` VALUES ('7', '2012-11-04 14:02:19', '112.00');
INSERT INTO `orders` VALUES ('8', '2012-10-29 14:02:19', '100.00');

SELECT
    WEEKDAY(`OrderDate`) AS `week_day`,
    COUNT(*) AS `sales_count`,
    SUM(`OrderValue`) AS `sales_value`
FROM `orders`
WHERE YEARWEEK(`OrderDate`) = YEARWEEK(NOW())
GROUP BY `week_day`
ORDER BY `week_day` ASC;

这是用于创建表的SQL,本周每天添加1个订单,但在星期一添加2个订单。以及用于获取报告的查询。

AND HERE' SQLFIDDLE.COM SAMPLE