[Complex SQL case - row and column conversion]

The source of the MYSQL case, thanks to the case provided by netizens, based on it, simplified, although it does not meet the database paradigm, but it is enough to explain the problem

 The original requirements are as follows:



 

The known source table data is as follows:

PID on one Place      
Apple 11 Beijing warehouse      
banana 22 Shanghai warehouse      
big pear 44 Guangzhou warehouse      
Apple 66 Shenzhen warehouse      

 

Now it is required to get the inventory report of each commodity, which is convenient for unified scheduling and display

PID Beijing warehouse Shanghai warehouse Guangzhou warehouse Shenzhen warehouse ……
Apple 11 0 0 66  
banana 0 22 0 0  
big pear 0 0 44 0  

 

 

Solution one:


 

Solution two:


 

 

Solution three:

 

 

Appendix:

/*

Navicat MySQL Data Transfer

 

Source Server         : localhost

Source Server Version : 50547

Source Host           : localhost:3306

Source Database       : db1

 

Target Server Type    : MYSQL

Target Server Version : 50547

File Encoding         : 65001

 

Date: 2017-07-09 17:58:13

*/

 

SET FOREIGN_KEY_CHECKS=0;

 

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

-- Table structure for `p`

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

DROP TABLE IF EXISTS `p`;

CREATE TABLE `p` (

  `id` int(11) NOT NULL DEFAULT '0',

  `pid` varchar(30) DEFAULT NULL,

  `num` int(11) DEFAULT NULL,

  `loc` varchar(30) DEFAULT NULL,

  PRIMARY KEY (`id`)

) ENGINE=MyISAM DEFAULT CHARSET=utf8;

 

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

-- Records of p

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

INSERT INTO `p` VALUES ('1', 'Apple', '11', 'Beijing warehouse');

INSERT INTO `p` VALUES ('2', 'banana', '22', 'Shanghai warehouse');

INSERT INTO `p` VALUES ('3', 'Da Yali', '44', 'Guangzhou warehouse');

INSERT INTO `p` VALUES ('4', 'Apple', '66', 'Shenzhen warehouse');

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326296717&siteId=291194637