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 に答える