Pull records from orders table for the current wee

2019-03-03 10:00发布

问题:

I have a table with the following info...

Id | orderNumber | orderDate | customerId

orderDate is a MySQL datetime field and the current day, month, year and time is inserted into the database at the time the record is written.

So my question is how would I pull a list of orders for a certain day of this current week. My goal is to use the google charts API to make a chart for "This Week's Sales" that says something like:

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

回答1:

Let's do exactly what you want:

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;

This returns a set of records with week_day and sale_count. Learn more here. Use NOW() if you use local datetime or use UTC_TIMESTAMP() if you play by GMT.

Do keep in mind I don't know your database name or the fields' names. You need to fill those in.

WORKING EXAMPLE:

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;

This is SQL to create a table, add 1 order per day for this week but 2 on Monday. And the query to fetch the report.

AND HERE'S SQLFIDDLE.COM SAMPLE.