SQL学习-sql谜题14(行变列)

如下表结构,需要查出每个emp的home number和fax number

/*
Cyper Data Studio
Date: 2014-03-16 10:51:56
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for PERSONNEL
-- ----------------------------
CREATE TABLE `personnel` (
  `emp_id` int(11) NOT NULL,
  `first_name` varchar(20) NOT NULL,
  `last_name` varchar(20) NOT NULL,
  PRIMARY KEY (`emp_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for PHONES
-- ----------------------------
CREATE TABLE `phones` (
  `emp_id` int(11) NOT NULL,
  `phone_type` varchar(3) NOT NULL,
  `phone_nbr` varchar(12) NOT NULL,
  PRIMARY KEY (`emp_id`,`phone_type`),
  CONSTRAINT `phones_ibfk_1` FOREIGN KEY (`emp_id`) REFERENCES `personnel` (`emp_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records for PERSONNEL
-- ----------------------------
INSERT INTO `PERSONNEL` VALUES ('1','cyper','yin');
INSERT INTO `PERSONNEL` VALUES ('2','will','zhang');
INSERT INTO `PERSONNEL` VALUES ('3','hong','liu');
INSERT INTO `PERSONNEL` VALUES ('4','kitten','wang');
-- ----------------------------
-- Records for PHONES
-- ----------------------------
INSERT INTO `PHONES` VALUES ('1','fax','3382111');
INSERT INTO `PHONES` VALUES ('1','hom','18672351111');
INSERT INTO `PHONES` VALUES ('2','hom','13812344321');
INSERT INTO `PHONES` VALUES ('3','fax','04111234');
INSERT INTO `PHONES` VALUES ('3','hom','041112345676');
INSERT INTO `PHONES` VALUES ('4','fax','3382111');
INSERT INTO `PHONES` VALUES ('4','hom','18672351111');


解法3 (行变列):

select
        E1.EMP_ID,
        E1.FIRST_NAME,
        E1.LAST_NAME,
        max(case              
            when p1.PHONE_TYPE = 'fax' then p1.PHONE_NBR              
            else null          
        end) as fax_phone,
        max(case              
            when p1.PHONE_TYPE = 'hom' then p1.PHONE_NBR              
            else null          
        end) as home_phone              
    from
        PERSONNEL E1             
    left outer join
        PHONES p1                            
            on p1.EMP_ID = e1.EMP_ID                 
    group by
        E1.EMP_ID,
        E1.FIRST_NAME,
        E1.LAST_NAME

Case when将1列变成两列
MAX合并之...看图说话

SQL学习-sql谜题14(行变列)

 

...

你可能感兴趣的:(sql)