在 MySQL 的单个查询中计算两个不同的列?
您可以使用CASE语句在单个查询中计算两个不同的列。为了理解这个概念,让我们首先创建一个表。创建表的查询如下。
mysql> create table CountDifferentDemo - > ( - > ProductId int NOT NULL AUTO_INCREMENT PRIMARY KEY, - > ProductName varchar(20), - > ProductColor varchar(20), - > ProductDescription varchar(20) - > );
使用插入命令在表中插入一些记录。
查询如下
mysql> insert into CountDifferentDemo(ProductName,ProductColor,ProductDescription) values('Product-1','Red','Used');
mysql> insert into CountDifferentDemo(ProductName,ProductColor,ProductDescription) values('Product-1','Blue','Used');
mysql> insert into CountDifferentDemo(ProductName,ProductColor,ProductDescription) values('Product-2','Green','New');
mysql> insert into CountDifferentDemo(ProductName,ProductColor,ProductDescription) values('Product-2','Blue','New');
mysql> insert into CountDifferentDemo(ProductName,ProductColor,ProductDescription) values('Product-3','Green','New');
mysql> insert into CountDifferentDemo(ProductName,ProductColor,ProductDescription) values('Product-4','Blue','Used');使用select语句显示表中的所有记录。
查询如下
mysql> select *from CountDifferentDemo;
以下是输出
+-----------+-------------+--------------+--------------------+ | ProductId | ProductName | ProductColor | ProductDescription | +-----------+-------------+--------------+--------------------+ | 1 | Product-1 | Red | Used | | 2 | Product-1 | Blue | Used | | 3 | Product-2 | Green | New | | 4 | Product-2 | Blue | New | | 5 | Product-3 | Green | New | | 6 | Product-4 | Blue | Used | +-----------+-------------+--------------+--------------------+ 6 rows in set (0.01 sec)
这是在单个查询中计算两个不同列的查询,即我们正在计算特定颜色“红色”和描述“新”的出现
mysql> select ProductName, - > SUM(CASE WHEN ProductColor = 'Red' THEN 1 ELSE 0 END) AS Color, - > SUM(CASE WHEN ProductDescription = 'New' THEN 1 ELSE 0 END) AS Desciption - > from CountDifferentDemo - > group by ProductName;
以下是输出
+-------------+-------+------------+ | ProductName | Color | Desciption | +-------------+-------+------------+ | Product-1 | 1 | 0 | | Product-2 | 0 | 2 | | Product-3 | 0 | 1 | | Product-4 | 0 | 0 | +-------------+-------+------------+ 4 rows in set (0.12 sec)
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下