mysql 行变列

 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

 摘自 http://space.itpub.net/82080

 

另外一法:

 

select a.cmp_name,a.dep_name1 from cmp a
union all
select a.cmp_name,a.dep_name2 from cmp a
union all
select a.cmp_name,a.dep_name3 from cmp a

union all
select a.cmp_name,a.dep_name4 from cmp a

union all
select a.cmp_name,a.dep_name5 from cmp a
order by cmp_name

posted on 2012-12-04 11:17  kenwong  阅读(160)  评论(0)    收藏  举报

导航