想知道是否有人可以提供帮助,我的SQL语句会让我感到悲伤。
我的声明使用MAX case()作为数据透视表,工作正常 - 但我手动应用AS列名称 - 这可以动态完成吗?
这是我目前的陈述;
SELECT
u.prefix AS 'Title',
u.forename AS 'Forename',
u.surname AS 'Surname',
u.email AS 'Email Address',
u.update_time AS 'Register Date',
eg.name AS 'Event Group Registered',
e.name AS 'Session Registered',
MAX(CASE WHEN uv.user_type_variables_id = 1 THEN uv.value ELSE NULL END) AS 'Question2',
MAX(CASE WHEN uv.user_type_variables_id = 2 THEN uv.value ELSE NULL END) AS 'Question2',
MAX(CASE WHEN uv.user_type_variables_id = 3 THEN uv.value ELSE NULL END) AS 'Question1',
MAX(CASE WHEN uv.user_type_variables_id = 4 THEN uv.value ELSE NULL END) AS 'Question2',
MAX(CASE WHEN uv.user_type_variables_id = 5 THEN uv.value ELSE NULL END) AS 'Question1',
MAX(CASE WHEN uv.user_type_variables_id = 6 THEN uv.value ELSE NULL END) AS 'Question2'
FROM tbl_event_attendees AS ea
LEFT JOIN tbl_user AS u ON ea.user_id = u.id
LEFT JOIN tbl_event AS e ON ea.event_id = e.id
LEFT JOIN tbl_event_groups AS eg on e.group_id = eg.id
LEFT JOIN tbl_user AS u2 ON ea.guest_of_user_id = u2.id
LEFT JOIN tbl_user_variables AS uv on u.id = uv.user_id
WHERE ea.event_id =6
GROUP BY ea.id
我的语句将几个表连接在一起,包括一个变量表,其中有几行适用于此表中的特定行。
所以我不希望列的名称是'问题1',而是相邻的列' name'适用于uv.value
,即。;
MAX(CASE WHEN uv.user_type_variables_id = 14 THEN uv.value ELSE NULL END) AS uv.name,
有谁能建议如何做到这一点?
答案 0 :(得分:0)
不确定它是否适合您,但只是尝试一下;)
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(CASE WHEN uv.user_type_variables_id = ''',
uv.user_type_variables_id,
''' THEN uv.value ELSE NULL END) AS `',
uv.name, '`'
)
) INTO @sql
FROM tbl_user_variables uv;
SET @sql = CONCAT('SELECT
u.prefix AS ''Title'',
u.forename AS ''Forename'',
u.surname AS ''Surname'',
u.email AS ''Email Address'',
u.update_time AS ''Register Date'',
eg.name AS ''Event Group Registered'',
e.name AS ''Session Registered'', ',
@sql,
' FROM tbl_event_attendees AS ea
LEFT JOIN tbl_user AS u ON ea.user_id = u.id
LEFT JOIN tbl_event AS e ON ea.event_id = e.id
LEFT JOIN tbl_event_groups AS eg on e.group_id = eg.id
LEFT JOIN tbl_user AS u2 ON ea.guest_of_user_id = u2.id
LEFT JOIN tbl_user_variables AS uv on u.id = uv.user_id
WHERE ea.event_id =6
GROUP BY ea.id');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;