Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Đếm 2 cột khác nhau trong 1 truy vấn MySQL

Dùng CASE WHEN ... THEN 1 ELSE 0 END bên trong SUM() để đếm điều kiện trên nhiều cột cùng lúc.

Tạo bảng:

mysql> CREATE TABLE CountDifferentDemo (
    -> ProductId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    -> ProductName VARCHAR(20),
    -> ProductColor VARCHAR(20),
    -> ProductDescription VARCHAR(20)
    -> );

Chèn dữ liệu:

mysql> INSERT INTO CountDifferentDemo(ProductName, ProductColor, ProductDescription) VALUES
    -> ('Product-1','Red','Used'), ('Product-1','Blue','Used'), ('Product-2','Green','New'),
    -> ('Product-2','Blue','New'), ('Product-3','Green','New'), ('Product-4','Blue','Used');

Hiển thị dữ liệu:

+-----------+-------------+--------------+--------------------+
| ProductId | ProductName | ProductColor | ProductDescription |
+-----------+-------------+--------------+--------------------+
| 1         | Product-1   | Red          | Used               |
| 2         | Product-1   | Blue         | Used               |
| 3         | Product-2   | Green        | New                |
| 4         | Product-2   | Blue         | New                |
| 5         | Product-3   | Green        | New                |
| 6         | Product-4   | Blue         | Used               |
+-----------+-------------+--------------+--------------------+

Truy vấn đếm màu "Red" và mô tả "New" theo từng sản phẩm:

mysql> SELECT ProductName,
    -> SUM(CASE WHEN ProductColor = 'Red' THEN 1 ELSE 0 END) AS Color,
    -> SUM(CASE WHEN ProductDescription = 'New' THEN 1 ELSE 0 END) AS Description
    -> FROM CountDifferentDemo GROUP BY ProductName;

Kết quả:

+-------------+-------+-------------+
| ProductName | Color | Description |
+-------------+-------+-------------+
| Product-1   | 1     | 0           |
| Product-2   | 0     | 2           |
| Product-3   | 0     | 1           |
| Product-4   | 0     | 0           |
+-------------+-------+-------------+