如何使用mysql统计记录
我有一张名为product的表格,如下所示如何使用mysql统计记录,mysql,sql,Mysql,Sql,我有一张名为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 prod
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
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
如何基于产品代码为此编写sql查询使用此
SELECT COUNT( DISTINCT product_code) FROM Product where product_code = 10;
SELECT COUNT( DISTINCT product_code) FROM Product where product_code = 20;
尝试以下查询:
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
使用子查询时有一点变化(因为我喜欢它们;): (顺便说一句,人们可能希望使用
COUNT()
进行计数可以更好地利用(公司代码、产品代码)上的潜在索引。我想这一点不太确定。)
制作
+--------------+--------------+------------+------------+
| 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)
如果希望这些列是动态的(交叉表/数据透视表),可以执行以下操作:
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;
第一条语句使用所有的和(xxx
创建@sql,然后执行新形成的sql语句。不管您有多少产品。但是请记住,如果您有很多产品,这种显示方式是不直观的
product_10和product_20是固定列,或者是动态的??在一般情况下,您正在寻找一个本机不支持的交叉表。但是,如果您有一组固定的产品代码,则有多种方法可以对其进行黑客攻击以获得您的结果。已修复,只需将(product_代码)这两种代码中的可用代码数作为product_10