0

这是一个与我原来的问题有关的问题

使用 MySQL 的数据透视表

表中的数据现在是这样保存的

我有两张桌子 Triples 和 Tags

Triples Table has the following Columns

  id  PostID  TagID   Value
   1   1        1     Murder
   2   1        1     Theft
   3   2        2     Knife 
   4   2        2     Gun 

标签表具有以下列

 id   TagName
  1   Incident
  2   Weapon

我正在尝试编写 sql 来创建带有动态标题的数据透视表

输出应该是这样的

   PostID  Incident              Weapon        
       1   Murder,Theft        
       2                          Knifie,Gun 

我为此编写了一个低效且部分 sql 查询,在编写此 sql 的任何帮助表示赞赏

   SET @sql = NULL;
     SELECT
       GROUP_CONCAT(DISTINCT
          CONCAT(
             'max(CASE WHEN TagName = ''',
              TagName,
              ''' THEN p.value END) AS `',
               TagName, '`'
               )
                ) INTO @sql
         FROM tags;


     SET @sql 
        = CONCAT('CREATE VIEW PostTags as SELECT p.postid, p.id, ', @sql, ' 
          from triples p
          left join tags t
            on p.tagid = t.id
            group by p.postid, p.id');

         PREPARE stmt FROM @sql;

     EXECUTE stmt;
     DEALLOCATE PREPARE stmt;
4

1 回答 1

1

您将必须构建两个字符串,一个用于内部旋转以创建 and 的列,Incident第二Weapon个字符串GROUP_CONCAT用于外部查询:

SET @sql = NULL;
SET @sql2 = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
            CONCAT(
             'group_concat(',
              TagName,
              ' separator '', '') as `',
               TagName, '`'
               )
    ) 
INTO @sql2
FROM tags;

SELECT
  GROUP_CONCAT(DISTINCT
            CONCAT(
             'max(CASE WHEN TagName = ''',
              TagName,
              ''' THEN p.value END) AS `',
               TagName, '`'
               )
    ) 
INTO @sql
FROM tags;

SET @sql = CONCAT('select postid, ', @sql2, '
                   from
                   (
                     SELECT p.postid, p.id, ', @sql, ' 
                     from triples p
                     left join tags t
                      on p.tagid = t.id
                      group by p.postid, p.id
                   ) d
                   group by postid');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

请参阅带有演示的 SQL Fiddle

这是创建 SQL 代码:

select postId,
  group_concat(incident separator ', ') incident,
  group_concat(Weapon separator ', ') Weapon
from
(
  SELECT p.postid, p.id, 
    max(CASE WHEN TagName = 'Incident' THEN p.value END) AS `Incident`,
    max(CASE WHEN TagName = 'Weapon' THEN p.value END) AS `Weapon` 
  from triples p 
  left join tags t 
    on p.tagid = t.id 
  group by p.postid, p.id
) d
group by postId;

请参阅带有演示的 SQL Fiddle

于 2013-06-21T21:43:05.693 回答