我有以下数据集:
project_type_id | total_hours | task_completion
-------------------------------------------------------
10 | 5 | 2018-9-10
10 | 4 | 2018-9-11
11 | 10 | 2018-9-10
12 | 2 | 2018-9-10
13 | 9 | 2018-9-10
14 | 8 | 2018-9-11
对于给定的total sum of hours
输入,我试图为数据集中的每个可用project_type
获取year
。
这是我的查询:
DROP PROCEDURE IF EXISTS getTaskHourReport;
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `getTaskHourReport`(IN `year` INT)
BEGIN
SET GLOBAL group_concat_max_len=4294967295;
SET @SQL = NULL;
SET @year = year;
SELECT
COALESCE(GROUP_CONCAT(DISTINCT
CONCAT(
'SUM(CASE WHEN project_type_id = "',project_type_id,'" THEN total_hours ELSE 0 END) AS `',project_type_id,'`'
)
), '0 as `NoMatchingRows`') INTO @SQL
FROM `task_details`
WHERE YEAR(task_completion) = @year;
SET @SQL
= CONCAT
(
'
SELECT ', @SQL, '
FROM
task_details
WHERE YEAR(task_completion) = @year
GROUP BY project_type_id
'
);
PREPARE stmt FROM @SQL;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;
此查询给我以下输出:
10 | 11 | 12 | 13 | 14
-------------------------------
9 | 0 | 0 | 0 | 0
0 | 10 | 0 | 0 | 0
0 | 0 | 2 | 0 | 0
0 | 0 | 0 | 9 | 0
0 | 0 | 0 | 0 | 8
预期输出:
10 | 11 | 12 | 13 | 14
-------------------------------
9 | 10 | 2 | 9 | 8
如何获得预期的单行?
答案 0 :(得分:3)
删除GROUP BY
。所以:
SET @SQL = CONCAT('SELECT ', @SQL, ' ',
'FROM task_details '
'WHERE YEAR(task_completion) = @year'
);
没有GROUP BY
的聚合查询将所有行视为一个组。因此,它仅返回一行。即使被引用的表为空或过滤条件删除了所有行,也是如此(在这种情况下,大多数聚合函数都返回NULL
,尽管COUNT()
返回0
)。