-1

我有一个名为 product 的表,如下所示

Product
company_code product_code product_name
100          10           bag
100          10           bag_2
100          10           bag_3
100          20           penci_l
100          20           pencil_1

我需要如下输出

company_code product_10 product_20
100          3           2

如何根据product_code为此编写sql查询

4

4 回答 4

2

尝试以下查询:

select company_code , 
SUM(case when product_code = 10 then 1 else 0 end) as product_10 , 
SUM(case when product_code = 20 then 1 else 0 end) as product_20
from product
group by company_code

SQLFIDDLE

于 2013-07-09T15:21:15.583 回答
0

用这个

SELECT COUNT( DISTINCT product_code) FROM Product where product_code = 10;

SELECT COUNT( DISTINCT product_code) FROM Product where product_code = 20;
于 2013-07-09T15:16:57.500 回答
0

使用子查询的轻微变化(因为我喜欢它们;):

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)
于 2013-07-09T16:09:35.570 回答
0

如果您希望这些列是动态的(交叉表/数据透视表),您可以执行以下操作:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'SUM(case when product_code = ', product_code,
      ' then 1 else 0 end) as product_', product_code
    )) INTO @sql
FROM product;

SET @sql = 
   CONCAT('SELECT company_code, ',
          @sql,
          ' FROM product',
          ' GROUP BY company_code');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

第一条语句创建@sql,SUM(xxx然后执行新形成的sql语句。您拥有多少产品并不重要。但请记住,如果您有很多产品,这种展示方式并不直观。

工作 SQL Fiddle 演示

于 2013-07-09T16:36:45.573 回答