mysql group by with one rows from a table

时间:2012-10-17 20:49:17

标签: mysql group-by pivot

  

可能重复:
  mysql converting multiple rows into columns in a single row

我有一个像这样的mysql表:

id |  p |  c  |  v
1     p1   10    1
2     p1   20    2
3     p1   30    3
4     p2   40    1
5     p2   50    2
6     p2   60    3

现在我需要运行一个sql并得到如下结果:

p  |  as_c1 | as_c2 | as_c3
p1     10       20      30
p2     40       50      60

我使用了这个查询,但这还不够:

select 
p, 
c as as_c1,
c as as_c2,
c as as_c3
from test_tbl group by p, c
我搜遍了每一个地方,这可能吗?我只需要一些指南。

2 个答案:

答案 0 :(得分:2)

这基本上是您尝试执行的PIVOT。不幸的是,MySQL没有PIVOT功能。静态或动态有两种方法。如果您知道要转换为列的值,则可以使用静态版本,但如果值未知,则可以使用预准备语句动态生成:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'sum(case when v = ''',
      v,
      ''' then c end) AS as_c',
      v
    )
  ) INTO @sql
FROM table1;

SET @sql = CONCAT('SELECT p, ', @sql, ' 
                    FROM table1 
                    GROUP BY p');

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

请参阅SQL Fiddle with Demo

静态版本与此类似:

select p,
  sum(case when v=1 then c end) as_c1,
  sum(case when v=2 then c end) as_c2,
  sum(case when v=3 then c end) as_c3
from table1
group by p

请参阅SQL Fiddle with Demo

答案 1 :(得分:0)

SELECT p,
  ( CASE WHEN v = 1 THEN c ELSE NULL END ) AS as_c1,
  ( CASE WHEN v = 2 THEN c ELSE NULL END ) AS as_c2,
  ( CASE WHEN v = 3 THEN c ELSE NULL END ) AS as_c3
FROM `test_tbl`
GROUP BY p;

我认为应该这样做。