我的问题是如何将行单元格输出分成不同的列,以便查看数据更具可读性。
我有以下SQL查询:
SELECT TD.name AS Conditions, PV.value AS Frequency, MSL.name AS
Mailing_List_Subscriptions, Count(CI.uid) AS Users_Signup_Count
FROM conditions_interest CI
INNER JOIN profile_values PV
ON CI.uid = PV.uid
INNER JOIN hwmailservice_user_lists MSUL
ON CI.uid = MSUL.uid
INNER JOIN hwmailservice_lists MSL
ON MSUL.list_id = MSL.list_id
INNER JOIN term_data TD
ON CI.tid = TD.tid
WHERE (PV.value = 'daily' OR PV.value = 'weekly') AND CI.email = '1'
GROUP BY PV.value, TD.name, MSL.name
ORDER BY TD.name;
使用以下输出:
因此,所有邮件列表订阅都有自己的单独列,其中包含与条件关联的计数。像这样:
Conditions Frequency Newsletter Partners Annoucements marketing
Abscessed Tooth Daily 95 91 98 98
Abscessed Tooth Weekly 6 4 7 7
如果需要更多说明,我会编辑我的帖子。
答案 0 :(得分:3)
MySQL没有PIVOT
功能,这就是你正在做的事情,因此你需要使用CASE
:
SELECT x.Conditions,
x.Frequency,
SUM(CASE WHEN Mailing_List_Subscriptions = 'newsletter' THEN Users_Signup_Count END) newsletter,
SUM(CASE WHEN Mailing_List_Subscriptions = 'partners' THEN Users_Signup_Count END) partners,
SUM(CASE WHEN Mailing_List_Subscriptions = 'announcements' THEN Users_Signup_Count END) announcements,
SUM(CASE WHEN Mailing_List_Subscriptions = 'marketing' THEN Users_Signup_Count END) marketing
FROM
(
SELECT TD.name AS Conditions, PV.value AS Frequency,
MSL.name AS Mailing_List_Subscriptions,
Count(CI.uid) AS Users_Signup_Count
FROM conditions_interest CI
INNER JOIN profile_values PV
ON CI.uid = PV.uid
INNER JOIN hwmailservice_user_lists MSUL
ON CI.uid = MSUL.uid
INNER JOIN hwmailservice_lists MSL
ON MSUL.list_id = MSL.list_id
INNER JOIN term_data TD
ON CI.tid = TD.tid
WHERE (PV.value = 'daily' OR PV.value = 'weekly') AND CI.email = '1'
GROUP BY PV.value, TD.name, MSL.name
) x
GROUP BY x.Conditions, x.Frequency
ORDER BY x.name