多行变成列转换

 mysql 多行变一行 若行与列转换

2008-10-16 09:42 345人阅读 评论(0) 收藏 举报

 DateClass       Class         Count   

  2004-02             AU                 32   

  2004-02             VAIO             56   

  2004-02             PB                 77   

  2004-02             TV                 89   

  2004-03             AU                 38   

  2004-03             VAIO             99   

  2004-03             PB                 32   

  2004-03             TV                 87   

  要将查询结果变为   

  DateClass         AU       VAIO         PB       TV   

  2004-02             32         56           77       89   

  2004-03             38         99           32       87  

建表:

CREATE TABLE `test` (

  `dataClass` varchar(25) DEFAULT NULL,

  `class` varchar(25) DEFAULT NULL,

  `count` varchar(25) DEFAULT NULL

);

-- ----------------------------

-- Records 

-- ----------------------------

INSERT INTO `test` VALUES ('2004-02', 'AU', '32');

INSERT INTO `test` VALUES ('2004-02', 'VAIO', '56');

INSERT INTO `test` VALUES ('2004-03', 'AU', '38');

INSERT INTO `test` VALUES ('2004-03', 'PB', '55');

SQL实现:

select   DataClass   ,     

                max(case   when   class   =   'AU'   then   Count   else   0   end)   as   AU,   

                max(case   when   class   =   'VAIO'   then   Count   else   0   end)   as   VAIO,   

                max(case   when   class   =   'PB'   then   Count   else   0   end)   as   PB,   

                max(case   when   class   =   'TV'   then   Count   else   0   end)   as   TV   

  from   test   

  group   by   DataClass;

结果:

+-----------+----+------+----+----+

| DataClass | AU | VAIO | PB | TV |

+-----------+----+------+----+----+

| 2004-02   | 32 | 56   | 0  | 0  |

| 2004-03   | 38 | 0    | 55 | 0  |

+-----------+----+------+----+----+

2 rows in set

猜你喜欢

转载自liuwang126.iteye.com/blog/1684777