我有以下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
并希望通过以下布局获得数据透视表:
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。我怎样才能获得所需的数据透视表结果?解决@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;
[删除了第二个问题,因为它已经用第一个答案解决了]