You can use IF() to GROUP BY multiple columns. To understand the concept, let us create a table. The query to create a table is as follows
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 some records in the table using insert command. The query is as follows −
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)
Display all records from the table using select statement. The query is as follows −
mysql> select *from MultipleGroupByDemo;
The output is as follows
+----+------------+-------------+ | 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)
Here is the query to GROUP BY multiple columns
mysql> SELECT CustomerId, if( ProductName = 'Product-2', 1, 0 ) -> FROM MultipleGroupByDemo -> GROUP BY ProductName , CustomerId;
The following is the output
+------------+---------------------------------------+ | CustomerId | if( ProductName = 'Product-2', 1, 0 ) | +------------+---------------------------------------+ | 1000 | 0 | | 1001 | 1 | | 1002 | 0 | | 1003 | 0 | +------------+---------------------------------------+ 4 rows in set (0.00 sec)
Here is an alternate query
mysql> select CustomerId,MAX(IF(ProductName = 'Product-2', 1,0)) from MultipleGroupByDemo group by CustomerId;
The following is the output
+------------+-----------------------------------------+ | CustomerId | MAX(IF(ProductName = 'Product-2', 1,0)) | +------------+-----------------------------------------+ | 1000 | 0 | | 1001 | 1 | | 1002 | 0 | | 1003 | 0 | +------------+-----------------------------------------+ 4 rows in set (0.00 sec)