如何在MySQL中将列名转换为结果集?

时间:2016-04-29 10:48:12

标签: mysql sql

我有一个查询

 SELECT 
    count(CASE WHEN fan_gate.genre = 'Breaks' THEN fan_gate.id END) AS 'Breaks',
    count(CASE WHEN fan_gate.genre = 'Cill Out' THEN fan_gate.id END) AS 'Chill Out',
    count(CASE WHEN fan_gate.genre = 'Deep House' THEN fan_gate.id END) AS 'Deep House',
    count(CASE WHEN fan_gate.genre = 'Drum & Bass' THEN fan_gate.id END) AS 'Drum & Bass'
FROM fan_gate

当前结果集

Breaks  | Cill Out  |Deep House  |Drum & Bass
------------------------------------------------
  4581  |    785    | 7858       |   4474

我需要

Column 1    | column 2
-----------------------
Breaks      | 4581
Cill Out    |  785
Deep House  | 7858
Drum & Bass | 4474

2 个答案:

答案 0 :(得分:1)

您只想要group by

SELECT fg.genre, COUNT(*)
FROM fan_gate fg
GROUP BY fg.genre;

如果您只关心这四种类型,请在WHERE之前添加GROUP BY条款,以选择您关注的类型。

答案 1 :(得分:0)

SELECT fan_gate.genre as column1,count(fan_gate.genre) as column2
FROM fan_gate
group by fan_gate.genre