MySQL 查询以按多列进行分组

mysqlmysqli database

您可以使用 IF() 按多列进行分组。为了理解这个概念,让我们创建一个表。创建表的查询如下

mysql> create table MultipleGroupByDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> CustomerId int,
   -> ProductName varchar(100)
   -> );
Query OK, 0 rows affected (0.59 sec)

使用 insert 命令在表中插入一些记录。 查询语句如下 −

mysql> insert into MultipleGroupByDemo(CustomerId,ProductName) values(1000,'Product-1');
Query OK, 1 row affected (0.20 sec)
mysql> insert into MultipleGroupByDemo(CustomerId,ProductName) values(1001,'Product-2');
Query OK, 1 row affected (0.18 sec)
mysql> insert into MultipleGroupByDemo(CustomerId,ProductName) values(1001,'Product-2');
Query OK, 1 row affected (0.16 sec)
mysql> insert into MultipleGroupByDemo(CustomerId,ProductName) values(1001,'Product-2');
Query OK, 1 row affected (0.12 sec)
mysql> insert into MultipleGroupByDemo(CustomerId,ProductName) values(1002,'Product-3');
Query OK, 1 row affected (0.09 sec)
mysql> insert into MultipleGroupByDemo(CustomerId,ProductName) values(1002,'Product-3');
Query OK, 1 row affected (0.15 sec)
mysql> insert into MultipleGroupByDemo(CustomerId,ProductName) values(1003,'Product-4');
Query OK, 1 row affected (0.16 sec)

使用 select 语句显示表中的所有记录。查询如下 −

mysql> select *from MultipleGroupByDemo;

输出如下

+----+------------+-------------+
| Id | CustomerId | ProductName |
+----+------------+-------------+
|  1 |       1000 | Product-1   |
|  2 |       1001 | Product-2   |
|  3 |       1001 | Product-2   |
|  4 |       1001 | Product-2   |
|  5 |       1002 | Product-3   |
|  6 |       1002 | Product-3   |
|  7 |       1003 | Product-4   |
+----+------------+-------------+
7 rows in set (0.00 sec)

这是对多列进行 GROUP BY 的查询

mysql> SELECT CustomerId, if( ProductName = 'Product-2', 1, 0 )
   -> FROM MultipleGroupByDemo
   -> GROUP BY ProductName , CustomerId;

以下是输出 −

+------------+---------------------------------------+
| CustomerId | if( ProductName = 'Product-2', 1, 0 ) |
+------------+---------------------------------------+
|       1000 |                                     0 |
|       1001 |                                     1 |
|       1002 |                                     0 |
|       1003 |                                     0 |
+------------+---------------------------------------+
4 rows in set (0.00 sec)

这是另一个查询

mysql> select CustomerId,MAX(IF(ProductName = 'Product-2', 1,0)) from MultipleGroupByDemo group by CustomerId;

以下是输出 −

+------------+-----------------------------------------+
| CustomerId | MAX(IF(ProductName = 'Product-2', 1,0)) |
+------------+-----------------------------------------+
|       1000 |                                       0 |
|       1001 |                                       1 |
|       1002 |                                       0 |
|       1003 |                                       0 |
+------------+-----------------------------------------+
4 rows in set (0.00 sec)

相关文章