【发布时间】:2013-06-06 21:15:17
【问题描述】:
我想要这样的东西:
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。谢谢!!!
【问题讨论】:
-
@barmar 我发现了很多数据透视表问题,但我不明白语法应该是怎样的。大多数示例只有透视列,从单个表中选择,并且没有 where 子句。
-
向查询添加透视列通常不会更改查询的这些部分。
-
@barmar 我尝试遵循msdn.microsoft.com/en-us/library/ms177410(v=sql.105).aspx 此处的语法,但不知道该为
[first pivoted column] AS <column name>输入什么,因为我没有列名。列名应该是我的“问题”。另外,我不知道该放什么 FROM。我会做类似的事情吗:FROM answer a, option o, box b, item i, user u,SELECT( ... ) AS sourceTablePIVOT ( ... ) AS pivotTable也不知道在 FOR 中放什么...我玩了几个小时但没有用。 -
MySQL 没有
PIVOT(),这就是为什么你必须做类似彼得回答的事情。 -
你必须在 MySQL 中解决这个问题吗?您是否使用编程语言执行查询,以便重新排列数据以显示在那里?