0

我整天都在忙。我玩过很多 MySQL 代码,我要么无能,要么不擅长编码。

我有一张桌子

name     id       type      amount
=================================
apple    21       cars      67
apple    21       bikes     85
apple    21       skates    557
apple    21       pajs      56
orange   34       bikes     345
orange   34       disks     678
orange   34       cars      234
orange   34       pajs      5678

我想写一个查询,以这种形式带回表格

name    id cars bikes skates pajas disks
=========================================
apple   21 67   85    557    56    0    
orange  34 234  345   0      5678  678

我真的不知道从哪里开始。对不起,如果这是一个菜鸟问题,但 MySQL 有时真的很难概念化。

4

1 回答 1

5

尝试使用PreparedStatement

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(ID),MAX(case when type = ''',
      type,
      ''' then amount ELSE NULL end) AS ',
       type
    )
  ) INTO @sql
FROM table1;

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

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

SQLFiddle 演示

或者,

SELECT  name,
        MAX(ID) ID,
        MAX(case when type = 'cars' THEN amount ELSE NULL end) AS cars,
        MAX(case when type = 'bikes' THEN amount ELSE NULL end) AS bikes,
        MAX(case when type = 'skates' THEN amount ELSE NULL end) AS skates,
        MAX(case when type = 'pajas' THEN amount ELSE NULL end) AS pajas,
        MAX(case when type = 'disks' THEN amount ELSE NULL end) AS disks
FROM table1 
GROUP BY name;

SQLFiddle 演示

于 2012-10-12T06:38:36.527 回答