它对你有用吗:
SELECT
COUNT(CASE WHEN red=1 THEN 1 END) as red_cnt,
COUNT(CASE WHEN green=1 THEN 1 END) as green_cnt,
COUNT(CASE WHEN blue=1 THEN 1 END) as blue_cnt
FROM table1
然后你可以在客户端以你想要的方式显示它。不幸的是,mysql 不支持PIVOT
或WITH
因此在服务器端旋转这样的结果将过于冗长。以您需要的方式生成结果集的另一种方法是使用UNION
. :
更新
我刚刚意识到还有另一种选择:
SELECT a.product,
CASE a.product
WHEN 'Red' THEN b.red_cnt
WHEN 'Blue' THEN b.blue_cnt
WHEN 'Green' THEN b.green_cnt
END as `Number`
FROM
(
SELECT 'Red' as product
UNION ALL
SELECT 'Blue'
UNION ALL
SELECT 'Green'
)a
LEFT JOIN
(
SELECT
COUNT(CASE WHEN red=1 THEN 1 END) as red_cnt,
COUNT(CASE WHEN green=1 THEN 1 END) as green_cnt,
COUNT(CASE WHEN blue=1 THEN 1 END) as blue_cnt
FROM table1
)b ON (1=1)