mysql - 枢轴查询不起作用

标签 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);

但我正在努力做到这一点:

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;

顺便说一句,将其放回同一个表中是不合理的。查询应该足够了。您还可以将其放入 View 或另一个表中。

编辑:

另一种方法是使用联接。查询有点复杂:

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 - 枢轴查询不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21406520/

相关文章:

python - Pandas:从数据框的行中获取标签并将其转换为列名

python 数据透视表 - 列是日期,应该正确排序

用于创建和合并数据库数据透视表的 Python Pandas For 循环

MySQL 用逗号等组合行值

mysql - 使用 MySQL 进行关系数据库设计

mysql - 在 woocommerce 数据库中手动输入订单?

sql - 使用动态 SQL 语句进行数据透视

mysql - 'NoneType' 对象没有属性 'cursor'

mysql - 五表连接?

r - 如何为整个数据框指定 pivot_wider?