Pull records from orders table for the current week

前端 未结 1 1447
傲寒
傲寒 2021-01-26 09:28

I have a table with the following info...

Id | orderNumber | orderDate | customerId

orderDate is a MySQL datetime field and the cu

相关标签:
1条回答
  • 2021-01-26 09:50

    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.

    0 讨论(0)
提交回复
热议问题