使用子查询的轻微变化(因为我喜欢它们;):
SELECT S.company_code, S.product_code,
SUM(IF(S.product_code = 10, S.C, 0)) AS `product_10`,
SUM(IF(S.product_code = 20, S.C, 0)) AS `product_20`
FROM (SELECT company_code, product_code, COUNT(*) AS C
FROM Product
GROUP BY company_code, product_code) AS S
GROUP BY S.company_code;
(顺便说一句,人们可能希望使用计数COUNT()
可以更好地利用(company_code,product_code)上的潜在索引。不确定,认为......)
生产...
+--------------+--------------+------------+------------+
| company_code | product_code | product_10 | product_20 |
+--------------+--------------+------------+------------+
| 100 | 10 | 3 | 2 |
| 200 | 10 | 1 | 0 |
| 300 | 20 | 0 | 2 |
+--------------+--------------+------------+------------+
3 rows in set (0.00 sec)
...来自该数据集:
mysql> select * from Product;
+--------------+--------------+--------------+
| company_code | product_code | product_name |
+--------------+--------------+--------------+
| 100 | 10 | bag |
| 100 | 10 | bag_2 |
| 100 | 10 | bag_3 |
| 100 | 20 | pencil |
| 100 | 20 | pencil_1 |
| 200 | 10 | bag |
| 300 | 20 | pencil |
| 300 | 20 | pencil_1 |
+--------------+--------------+--------------+
8 rows in set (0.00 sec)