mysql:列值作为select result中的列名

时间:2013-06-07 08:29:41

标签: mysql sql database

我有一个表,我按一列分组,然后输出不同的值和这些值的计数。

activty | sum
-------------
Form    |  1
Login   |  4
Reg     |  3

这是一个示例代码:http://sqlfiddle.com/#!2/c6faf/2/0

但我想要不同的值tp列名称带有一行值(计数)。

像这样:

Form | Login | Reg
------------------
  1  |   4   |  3

我尝试了PIVOT操作,但我没有让它正常工作。我做错了什么?

这是我的代码:http://sqlfiddle.com/#!2/c6faf/35/0

提前感谢!

BR

3 个答案:

答案 0 :(得分:2)

你去吧

SELECT 
MAX(CASE activity WHEN 'Form' THEN mysum ELSE NULL END) AS Form,
MAX(CASE activity WHEN 'Login' THEN mysum ELSE NULL END) AS Login,
MAX(CASE activity WHEN 'Reg' THEN mysum ELSE NULL END) AS Reg
FROM (
SELECT activity, COUNT(activity) AS mysum FROM tbl_tracking
            WHERE id = 141 AND variant = 2
            GROUP BY activity
)sq

但在我看来,这种格式化应该在应用层进行,而不是在数据库层进行。

答案 1 :(得分:1)

试试这个:

SELECT  
    SUM(IF(activity = 'Form',1,0)) as 'Form',
    SUM(IF(activity = 'Login',1,0)) as 'Login',
    SUM(IF(activity = 'Reg',1,0)) as 'Reg'
FROM 
    tbl_tracking
WHERE 
    id = 141 
    AND variant = 2

Sql Fiddle here

答案 2 :(得分:0)

为此,您需要使用数据透视表概念。在这里你也是这样。

SELECT
  SUM((IF(activity='Form',1,0))) as Form,
  SUM((IF(activity='Login',1,0))) as Login,
  SUM((IF(activity='Reg',1,0))) as Reg
FROM 
  tbl_tracking
WHERE 
  id = 141 
  AND 
  variant = 2;

fiddle