简体   繁体   English

Pivot MySQL 表设置 boolean 值

[英]Pivot MySQL table setting boolean values

I have to perform what I think is a very basic MYSQL table pivot, but I am completely new to sql so I am not sure about the syntax.我必须执行我认为非常基本的 MYSQL 表 pivot,但我对 sql 完全陌生,所以我不确定语法。 I have the following table我有下表

record_id tag_id
id_1      tag1
id_1      tag2
id_2      tag1
id_2      tag3

I would like to obtain a pivoted table, whose rows are the unique record_ids, the columns are the unique tag_ids, and the values are boolean true/false if that record_id has that tag.我想获得一个数据透视表,其行是唯一的 record_ids,列是唯一的 tag_ids,如果 record_id 具有该标签,则值为 boolean true/false。 In this case, the expected result would be:在这种情况下,预期结果将是:

record_id tag1  tag2  tag3
id_1      true  true  false
id_2      true  false true

How can I achieve this?我怎样才能做到这一点?

Further question: what if I have another table that associates tag_names to tag_id, and I would like the columns of my pivoted table to be named after tag_names?进一步的问题:如果我有另一个将 tag_names 关联到 tag_id 的表,并且我希望我的透视表的列以 tag_names 命名怎么办? In this example, starting from在这个例子中,从

tag_id tag_name
tag1   tag_name1
tag2   tag_name2
tag3   tag_name3

I would finally get我最终会得到

record_id tag_name1  tag_name2  tag_name3
id_1      true       true       false
id_2      true       false      true

I appreciate any help.我感谢任何帮助。

SELECT record_id,
       CASE WHEN SUM(tag_id = 'tag1') THEN 'true' ELSE 'false' END tag1,
       CASE WHEN SUM(tag_id = 'tag2') THEN 'true' ELSE 'false' END tag2,
       CASE WHEN SUM(tag_id = 'tag3') THEN 'true' ELSE 'false' END tag3
FROM source_table
GROUP BY record_id
ORDER BY record_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM