0

我在数据库中有三列 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 中解决吗?

4

1 回答 1

3

您将需要加入您的表两次以获得groupand places,然后您可以使用带有 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

于 2013-08-06T13:09:14.197 回答