Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

MySQL: จัดกลุ่มข้อมูลตามวันที่ด้วย GROUP BY และฟังก์ชันวันที่

สร้างตารางและข้อมูลตัวอย่าง

mysql> create table DemoTable2002 ( CustomerName varchar(20), CustomerShippingDate datetime );
mysql> insert into DemoTable2002 values('Chris','2019-01-10');
mysql> insert into DemoTable2002 values('David','2018-12-31');
mysql> insert into DemoTable2002 values('David','2019-12-16');
mysql> insert into DemoTable2002 values('Chris','2018-12-01');

ข้อมูลในตาราง

+--------------+----------------------+
| CustomerName | CustomerShippingDate |
+--------------+----------------------+
| Chris        | 2019-01-10 00:00:00  |
| David        | 2018-12-31 00:00:00  |
| David        | 2019-12-16 00:00:00  |
| Chris        | 2018-12-01 00:00:00  |
+--------------+----------------------+

Query จัดกลุ่มตาม CustomerName หาวันที่ Min/Max

mysql> select date(min(CustomerShippingDate)), date(max(CustomerShippingDate)), CustomerName
    from DemoTable2002 group by CustomerName;

ผลลัพธ์

+---------------------------------+---------------------------------+--------------+
| date(min(CustomerShippingDate)) | date(max(CustomerShippingDate)) | CustomerName |
+---------------------------------+---------------------------------+--------------+
| 2018-12-01                      | 2019-01-10                      | Chris        |
| 2018-12-31                      | 2019-12-16                      | David        |
+---------------------------------+---------------------------------+--------------+

อธิบาย

  • GROUP BY CustomerName จับกลุ่มตามชื่อลูกค้า
  • MIN(CustomerShippingDate) หาวันที่ส่งของครั้งแรก (เก่าสุด)
  • MAX(CustomerShippingDate) หาวันที่ส่งของล่าสุด
  • DATE(...) แปลง DATETIME ให้เหลือเฉพาะ DATE

ขยาย: จัดกลุ่มตามเดือน/ปี

-- จัดกลุ่มตามเดือน
SELECT CustomerName, DATE_FORMAT(CustomerShippingDate, '%Y-%m') AS YearMonth, COUNT(*) AS ShipmentCount
FROM DemoTable2002 GROUP BY CustomerName, YearMonth;

-- จัดกลุ่มตามปี
SELECT CustomerName, YEAR(CustomerShippingDate) AS Year, COUNT(*) AS ShipmentCount
FROM DemoTable2002 GROUP BY CustomerName, Year;

กรณีต้องการนับวันที่ไม่ซ้ำกัน (Distinct Dates)

SELECT CustomerName, COUNT(DISTINCT DATE(CustomerShippingDate)) AS UniqueShipDays
FROM DemoTable2002 GROUP BY CustomerName;