Mysql pivot查询不使用';行不通
我有生以来第一次尝试在数据库表上使用PIVOT。 这是表格:Mysql pivot查询不使用';行不通,mysql,pivot,Mysql,Pivot,我有生以来第一次尝试在数据库表上使用PIVOT。 这是表格: Answers (id_user, id_question, topic, value) VALUES (1, 1, 'a', 3), (1, 1, 'b', 3), (1, 1, 'c', 2), (1, 2, 'a', 1), (1, 2, 'b', 2), (1, 2, 'c', 3), [...] (1, 14, 'a', 1), (1, 14, 'b', 2), (1, 14, 'c', 1); 但我想说的是: An
Answers (id_user, id_question, topic, value) VALUES
(1, 1, 'a', 3),
(1, 1, 'b', 3),
(1, 1, 'c', 2),
(1, 2, 'a', 1),
(1, 2, 'b', 2),
(1, 2, 'c', 3),
[...]
(1, 14, 'a', 1),
(1, 14, 'b', 2),
(1, 14, 'c', 1);
但我想说的是:
Answers (id_user, id_question, topic_A, topic_B, topic_C) VALUES
(1, 1, 3, 3, 2),
(1, 2, 1, 2, 3),
[...]
(1, 14, 1, 2, 1);
通过这个查询,我在PIVOT附近得到了一个通用语法错误
SELECT *
FROM
( SELECT id_user, id_question, topic, value
FROM Answers
WHERE id_user=98
) as risp
PIVOT
( FOR id_question IN ([a],[b],[c])
) AS pvt
在MySQL中使用聚合实现此目的的一种方法:
select id_user, id_question,
max(case when topic = 'A' then value end) as topic_A,
max(case when topic = 'B' then value end) as topic_B,
max(case when topic = 'C' then value end) as topic_C
from Answers a
group by id_user, id_question;
顺便说一下,把这个放回同一张桌子上是不合理的。查询应该足够了。您还可以将其放入视图或其他表中
编辑:
另一种方法是使用联接。查询有点复杂:
select uq.id_user, uq.id_question, aa.value as topic_A,
ab.value as topic_B, ac.value as topic_C
from (select distinct id_user, id_question from answers) uq left outer join
Answers aa
on aa.id_user = uq.id_user and aa.id_question = uq.id_question and
aa.topic = 'A' left outer join
Answers ab
on ab.id_user = uq.id_user and ab.id_question = uq.id_question and
ab.topic = 'B' left outer join
Answers aa
on ac.id_user = uq.id_user and ac.id_question = uq.id_question and
ac.topic = 'C';
MySQL对我所知道的内容没有
PIVOT
查询。@MatteoTassinari,右-PIVOT
语法适用于Microsoft SQL Server,其他SQL实现不支持它。有其他方法可以做到这一点吗?编辑:谢谢你的回答,我正在看你的帖子linked@BillKarwin . . . Oracle 11g还支持pivot
@GordonLinoff,感谢您的更正!干杯。第一个查询很有效,而第二个则不起作用。没有结果,phpmyadmin重新加载页面而不显示任何内容。然而,第一个是完美的!谢谢@用户3160178。我还是喜欢第一个版本。