mysql 枢轴 table 对选定行进行连接和枢轴计数
mysql pivot table with concat AND pivot counting of selected rows
我有以下 mysql-table cars
布局
BRAND | TYPE | COLOR
-----------------------
bmw | e30 | red
bmw | e90 | blue
bmw | e12 | red
audi | a3 | green
bmw | e90 | red
audi | tt | blue
bmw | e12 | blue
audi | a3 | green
并希望有一个枢轴 table 作为结果,具有以下布局:
brand_type | red | blue | green | total
-------------------------------------------
bmw-e30 | 1 | 0 | 0 | 1
bmw-e90 | 1 | 1 | 0 | 2
bmw-e12 | 1 | 1 | 0 | 2
audi-a3 | 0 | 0 | 2 | 2
audi-tt | 0 | 1 | 1 | 2
我最多能达到这个查询:
SELECT brand,
sum(if(color = 'red', 1, 0)) as red,
sum(if(color = 'blue', 1, 0)) as blue,
sum(if(color = 'green', 1,0)) as green,
count(color) as total
FROM `cars` group by brand;
结果为:
brand | red | blue | green | total
-------------------------------------------
bmw | 3 | 2 | 0 | 5
audi | 0 | 1 | 3 | 4
我已经在网上搜索过了,但我找不到任何连接 2 列(品牌和类型)的解决方案
AND 用于数据透视结果
1.我怎样才能达到我想要的枢轴 table 结果? 在@kevinsjöberg
的提示下解决了
SELECT concat(brand, '-', type) as BT,
sum(if(color = 'red', 1, 0)) as red,
sum(if(color = 'blue', 1, 0)) as blue,
sum(if(color = 'green', 1,0)) as green,
count(color) as total
FROM `cars` group by BT;
[删除了第二个问题,因为第一个答案已经解决了]
使用 MySQL 中的 CONCAT 函数。
CONCAT(`BRAND`, '-', `TYPE`)
然后你 GROUP BY brand
和 type
.
我有以下 mysql-table cars
布局
BRAND | TYPE | COLOR
-----------------------
bmw | e30 | red
bmw | e90 | blue
bmw | e12 | red
audi | a3 | green
bmw | e90 | red
audi | tt | blue
bmw | e12 | blue
audi | a3 | green
并希望有一个枢轴 table 作为结果,具有以下布局:
brand_type | red | blue | green | total
-------------------------------------------
bmw-e30 | 1 | 0 | 0 | 1
bmw-e90 | 1 | 1 | 0 | 2
bmw-e12 | 1 | 1 | 0 | 2
audi-a3 | 0 | 0 | 2 | 2
audi-tt | 0 | 1 | 1 | 2
我最多能达到这个查询:
SELECT brand,
sum(if(color = 'red', 1, 0)) as red,
sum(if(color = 'blue', 1, 0)) as blue,
sum(if(color = 'green', 1,0)) as green,
count(color) as total
FROM `cars` group by brand;
结果为:
brand | red | blue | green | total
-------------------------------------------
bmw | 3 | 2 | 0 | 5
audi | 0 | 1 | 3 | 4
我已经在网上搜索过了,但我找不到任何连接 2 列(品牌和类型)的解决方案 AND 用于数据透视结果
1.我怎样才能达到我想要的枢轴 table 结果? 在@kevinsjöberg
的提示下解决了SELECT concat(brand, '-', type) as BT,
sum(if(color = 'red', 1, 0)) as red,
sum(if(color = 'blue', 1, 0)) as blue,
sum(if(color = 'green', 1,0)) as green,
count(color) as total
FROM `cars` group by BT;
[删除了第二个问题,因为第一个答案已经解决了]
使用 MySQL 中的 CONCAT 函数。
CONCAT(`BRAND`, '-', `TYPE`)
然后你 GROUP BY brand
和 type
.