รวมยอดตามวันที่: GROUP BY Date + SUM()
จัดกลุ่มแถวที่มี ProductPurchaseDate เดียวกัน แล้ว SUM(NumberOfProduct) เพื่อหายอดรวมต่อวัน
สร้างตารางและข้อมูล
mysql> CREATE TABLE DemoTable1522 (
-> ProductPurchaseDate DATE,
-> NumberOfProduct INT
-> );
Query OK, 0 rows affected (1.51 sec)
mysql> INSERT INTO DemoTable1522 VALUES
-> ('2019-01-21', 45), ('2018-12-31', 78), ('2019-01-21', 67),
-> ('2019-03-01', 56), ('2018-01-21', 97), ('2019-01-21', 47);
Query OK, 6 rows affected
ข้อมูลก่อนจัดกลุ่ม
+---------------------+-----------------+ | ProductPurchaseDate | NumberOfProduct | +---------------------+-----------------+ | 2019-01-21 | 45 | | 2018-12-31 | 78 | | 2019-01-21 | 67 | | 2019-03-01 | 56 | | 2018-01-21 | 97 | | 2019-01-21 | 47 | +---------------------+-----------------+
คำสั่ง: GROUP BY Date + SUM
mysql> SELECT ProductPurchaseDate, SUM(NumberOfProduct)
-> FROM DemoTable1522
-> GROUP BY ProductPurchaseDate;
ผลลัพธ์
+---------------------+----------------------+ | ProductPurchaseDate | sum(NumberOfProduct) | +---------------------+----------------------+ | 2019-01-21 | 159 | | 2018-12-31 | 78 | | 2019-03-01 | 56 | | 2018-01-21 | 97 | +---------------------+----------------------+
การคำนวณยืนยัน
- 2019-01-21: 45 + 67 + 47 = 159
- 2018-12-31: 78
- 2019-03-01: 56
- 2018-01-21: 97
ขยาย: เรียงตามวันที่ และเพิ่มฟังก์ชันสรุปอื่น
SELECT
ProductPurchaseDate,
SUM(NumberOfProduct) AS total_products,
COUNT(*) AS transaction_count,
AVG(NumberOfProduct) AS avg_products,
MIN(NumberOfProduct) AS min_products,
MAX(NumberOfProduct) AS max_products
FROM DemoTable1522
GROUP BY ProductPurchaseDate
ORDER BY ProductPurchaseDate;
⚠️ หากคอลัมน์เป็น DATETIME ต้องการจัดกลุ่มตาม Date เท่านั้น
GROUP BY DATE(ProductPurchaseDate) -- หรือ GROUP BY CAST(ProductPurchaseDate AS DATE)
Index สำหรับ Query นี้
CREATE INDEX idx_purchase_date ON DemoTable1522(ProductPurchaseDate);