2

我想要看起来像这样的东西:

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。谢谢!!!

4

1 回答 1

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`
于 2013-06-11T05:53:49.840 回答