你已經接受了答案,但只是爲了好玩,如果你想動態生成的列名,因此,如果被輸入的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//
+1偉大的思想思考。 –
非常感謝。我只是修改了查詢以適合我的需求。我用COUNT取代了總數。 :) – maikelsabido