与MySQL Group By values that are equal over multiple columns类似
如何使用MySQL将下面的mysql数据库表转换为输出:
id entity_id volunteer_1 volunteer_2 volunteer_3
1 1540 1933 1253 2543
2 1638 2543 2123 1736
3 1736 1253 1933 2123
4 1834 1525 1253 2123
5 1932 2123 2543 2451
6 2030 2854 2451 1933
7 2128 2451 2854 2543
到输出
Jan-15 Feb-16 Mar-16
Actual Name 1 3 4 6
Actual Name 2 3 3 5
Actual Name 3 1 5 6
注意事项:
答案 0 :(得分:0)
首先通过联合解决,以获得建议答案的数据(单列格式)。建议的答案并未合并来自多列的类似数据。然后,您可以使用临时结果并根据需要进行转换。此外,它必须是一个存储过程,对于不会执行结果的语句。
DELIMITER $$
DROP PROCEDURE IF EXISTS `civicrm_report_tmp_volunteer`$$
CREATE PROCEDURE `civicrm_report_tmp_volunteer`()
BEGIN
DROP TABLE IF EXISTS civicrm_report_tmp_volunteer_hours;
SET @group_concat_max_len = 5000;
CREATE TEMPORARY TABLE civicrm_report_tmp_volunteer_hours AS
SELECT
CONCAT(c.first_name, ' ' , c.last_name) as contact_name,
a.contact_id as contact_id,
EXTRACT( YEAR_MONTH FROM ca.activity_date_time ) as sort_date,
CONCAT(
MONTHNAME(STR_TO_DATE(EXTRACT( MONTH FROM ca.activity_date_time), '%m')),
"-",
EXTRACT( YEAR FROM ca.activity_date_time )) as month_year,
-- a.activity_id,
-- ca.activity_type_id,
-- ca.activity_date_time,
-- ca.duration,
SUM(ca.duration) as activity_duration,
COUNT(DISTINCT (a.activity_id)) activity_count
FROM
(
SELECT volunteer_1_543 as contact_id, entity_id as activity_id FROM civicrm_value_volunteer_details_103
WHERE volunteer_1_543 IS NOT NULL
UNION
SELECT volunteer_2_544 as contact_id, entity_id as activity_id FROM civicrm_value_volunteer_details_103
WHERE volunteer_2_544 IS NOT NULL
UNION
SELECT volunteer_3_545 as contact_id, entity_id as activity_id FROM civicrm_value_volunteer_details_103
WHERE volunteer_3_545 IS NOT NULL
UNION
SELECT volunteer_4_546 as contact_id, entity_id as activity_id FROM civicrm_value_volunteer_details_103
WHERE volunteer_4_546 IS NOT NULL
) as a
LEFT JOIN civicrm_activity ca
ON a.activity_id = ca.id
LEFT JOIN civicrm_contact c
ON c.id = a.contact_id
WHERE ca.activity_type_id IN (184)
GROUP BY a.contact_id, month_year;
SET @query = null;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(IF(sort_date = ''',
sort_date,
''', activity_duration, 0)) AS ',
"'", month_year, "' "
)
) INTO @query
FROM civicrm_report_tmp_volunteer_hours;
SET @query = CONCAT('SELECT contact_name, ', @query , ' FROM civicrm_report_tmp_volunteer_hours GROUP BY contact_id');
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;
CALL civicrm_report_tmp_volunteer();