我想要一些看起来像这样的东西:
Group | ID | Date | Time | Phone Number | How tired are you? | How happy are you? |
1 | A23 | 1/1/12 | 5:30:00 | 8001231234 | 5 | 8 |
然而,我得到了这个:
Group | ID | Date | Time | Phone Number | Question | Answer |
1 | A23 | 1/1/12 | 5:30:00 | 8001231234 | How tired are you? | 5 |
1 | A23 | 1/1/12 | 5:30:00 | 8001231234 | How happy are you? | 8 |
我查了很多可能的解决方案,并知道我必须使用Pivot这样的情况。但是,我无法使语法工作。以下是我目前的代码:
SELECT
CASE when a.send_time between '2012-1-1 00:00:00' and '2012-1-2 23:59:59' then 1
else 2
end as "group",
u.id AS ID,
cast(a.send_time as date) AS "Date",
cast(a.send_time as time) AS "Time",
u.cellphone AS "Phone Number",
i.question AS "Question",
a.answer AS "Answer"
FROM
answer a, option o, box b, item i, user u
WHERE
a.id = b.id and
a.item_id = i.item_id and
o.item_id = a.item_id and
o.value = a.answer and
u.id = a.user_id;
我正在使用MySQL。谢谢!!!
答案 0 :(得分:3)
尝试
SELECT q.`Group`, q.`ID`, q.`Date`, q.`Time`, q.`Phone Number`,
MIN(CASE WHEN Question = 'How tired are you?' THEN Answer ELSE NULL END) `How tired are you?`,
MIN(CASE WHEN Question = 'How happy are you?' THEN Answer ELSE NULL END) `How happy are you?`
FROM
(
SELECT
CASE when a.send_time between '2012-1-1 00:00:00' AND '2012-1-2 23:59:59' then 1
ELSE 2 END as `group`,
u.id AS ID,
cast(a.send_time as date) AS `Date`,
cast(a.send_time as time) AS `Time`,
u.cellphone AS `Phone Number`,
i.question AS `Question`,
a.answer AS `Answer`
FROM
answer a, option o, box b, item i, user u
WHERE
a.id = b.id and
a.item_id = i.item_id and
o.item_id = a.item_id and
o.value = a.answer and
u.id = a.user_id;
) q
GROUP BY q.`Group`, q.`ID`, q.`Date`, q.`Time`, q.`Phone Number`