0

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

Id | orderNumber | orderDate | customerId

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

所以我的问题是如何提取本周某一天的订单列表。我的目标是使用谷歌图表 API 为“本周的销售”制作一个图表,上面写着:

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

1 回答 1

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_day和的记录sale_count 在这里了解更多。如果您使用NOW()本地日期时间或使用UTC_TIMESTAMP()GMT 播放,请使用。

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

工作示例:

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 个订单。以及获取报告的查询。

是 SQLFIDDLE.COM示例

于 2012-10-29T02:26:28.547 回答