如何从mySQL表中分组/总数据?

时间:2013-12-18 04:01:04

标签: php mysql sql

我在数据库中有一个表,我想在其上执行mySQL查询。这是表格的样子:

https://docs.google.com/spreadsheet/ccc?key=0At5_g34zSM41dFlNWUdNQnRPandiUUFuaUJzTEc1REE&usp=sharing

鉴于此表,我想显示每个旅程和目标名称的用户总数/数量。

我尝试过使用GROUP BY和COUNT,但我只得到了这个:

enter image description here

如您所见,数据仅按目标名称分组。有没有办法通过mySQL查询实现这种结果:? (见下图)

enter image description here

像这样的东西。我希望你能帮助我。提前谢谢!

3 个答案:

答案 0 :(得分:2)

您需要将PIVOT列添加到行中。不幸的是,MySQL没有PIVOT表运算符。但您可以使用CASE表达式来执行此操作,例如 -

SELECT
  journey,
  SUM(CASE WHEN  goalname = 'Frank.net Hospital Cash Back' THEN count END) AS `Frank.net Hospital Cash Back`,
  SUM(CASE WHEN  goalname = 'Frank.net Life Cover' THEN count END) AS `Frank.net Life Cover`,
  SUM(CASE WHEN  goalname = 'Frank.net Salary Protection' THEN count END) AS `Frank.net Salary Protection`,
  SUM(CASE WHEN  goalname = 'King Price Car Insurance' THEN count END) AS `King Price Car Insurance`
FROM test
GROUP BY journey;

SQLFiddle示例 - http://sqlfiddle.com/#!2/314c6/8

答案 1 :(得分:0)

以下查询可能适用于您的情况。

SELECT 
a.journey, 
a.goalname, 
FIND_IN_SET(a.goalname, (SELECT GROUP_CONCAT(goalname) FROM <table_name> b.journey =  a.journey)) AS no_of_goalname
FROM <table_name> a

答案 2 :(得分:0)

您已经接受了答案,但只是为了好玩,如果您想动态生成列名,那么如果输入goalName的新条目,则无需更改代码使用下面的(sqlFiddle

DROP PROCEDURE IF EXISTS  getCount//
CREATE PROCEDURE getCount ()
BEGIN
  -- First we declare all the variables we will need
  DECLARE loopGoalName VARCHAR(100);
  DECLARE dynamicSql VARCHAR(5000);
  DECLARE finalSql VARCHAR(5000);
  -- flag which will be set to true, when cursor reaches end of table
  DECLARE exit_loop BOOLEAN;         

  -- Declare the sql for the cursor
  DECLARE example_cursor CURSOR FOR
    SELECT DISTINCT goalName
    FROM YourTableName;

  -- Let mysql set exit_loop to true, if there are no more rows to iterate
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET exit_loop = TRUE;
  SET dynamicSql = '';
  SET finalSql = '';
  -- open the cursor
  OPEN example_cursor;

  -- marks the beginning of the loop
  example_loop: LOOP

    -- read the name from next row into the variable l_name
    FETCH  example_cursor INTO loopGoalName;
    -- check if the exit_loop flag has been set by mysql, 
    -- if it has been set we close the cursor and exit 
    -- the loop
    IF exit_loop THEN
        CLOSE example_cursor;
        LEAVE example_loop;
    END IF;
    SET DynamicSql = CONCAT(DynamicSql,",SUM(IF(goalName='",loopGoalName,"',1,0)) as `",loopGoalName,"`");
  END LOOP example_loop;
  SET finalSql = CONCAT('SELECT journey',DynamicSql,
                         ' FROM yourTableName
                           GROUP BY journey');
  -- now we run set some variables and run the dynamically built query
  SET @finalSql = finalSql;
  PREPARE stmt1 FROM @finalSql;
  EXECUTE stmt1;
END//