Mysql查询以矩阵的形式提取数据

时间:2013-08-06 13:04:37

标签: mysql matrix pivot-table

我在数据库中有三列id,topic和subtopic的数据。像这样的东西,

CREATE TABLE Table2 (`id` int, `topic` varchar(5), `subtopic` varchar(6));
INSERT INTO Table2 (`id`, `topic`, `subtopic`) VALUES
    (1, 'place', 'paris'),
    (1, 'group', 'A'),
    (1, 'group', 'B'),
    (2, 'place', 'us'),
    (2, 'group', 'C'),
    (3, 'group', 'A'),
    (3, 'water', 'salt'),
    (4, 'water', 'sweet'),
    (4, 'world', 'ep'),
    (5, 'place', 'venus'),
    (5, 'place', 'paris'),
    (5, 'group', 'A');

我想从主题输出结果矩阵位置组。这样的事情。

    Paris|US|Venus
A   2    |0 | 1
B   1    |0 | 0
C   0    |1 | 0

想法是在子主题栏中获取“组”(A,B,C)和“位置”(巴黎,我们,维纳斯)的所有值。然后找出具有这种条件的共现次数。

知道如何在MySql中解决?

1 个答案:

答案 0 :(得分:3)

您需要两次加入您的表以获取groupplaces,然后您可以使用带有CASE表达式的聚合函数将行转换为列:

select g.subtopic as `group`,
  sum(case when p.subtopic = 'Paris' then 1 else 0 end) Paris,
  sum(case when p.subtopic = 'US' then 1 else 0 end) US,
  sum(case when p.subtopic = 'Venus' then 1 else 0 end) Venus
from table2 g
left join table2 p
  on g.id = p.id
  and p.topic = 'place'
where g.topic = 'group'
group by g.subtopic;

SQL Fiddle with Demo

如果您要为subtopic创建未知值,则可以使用预准备语句和动态SQL:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'sum(case when p.subtopic = ''',
      subtopic,
      ''' then 1 else 0 end) as `', 
      subtopic, '`')
  ) INTO @sql
FROM table2
where topic = 'place';

SET @sql = CONCAT('SELECT g.subtopic as `group`, ', @sql, ' 
                  from table2 g
                  left join table2 p
                    on g.id = p.id
                    and p.topic = ''place''
                  where g.topic = ''group''
                  group by g.subtopic');

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

请参阅SQL Fiddle with Demo