首页 > 代码库 > MYSQL分段统计

MYSQL分段统计

产品表

CREATE TABLE `product` (

  `product_id` int(11) NOT NULL AUTO_INCREMENT,

  `product_model` varchar(255) NOT NULL,

   `product_price` decimal(15,4) NOT NULL,  

   `product_status` tinyint(1) unsigned NOT NULL,

   `product_add_time` int(11) unsigned DEFAULT ‘0‘,

  PRIMARY KEY (`product_id`),

  KEY `product_price` (`product_price`) USING BTREE

) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=utf-8
分类表

CREATE TABLE `category` (

    `category_id` int(11) unsigned NOT NULL AUTO_INCREMENT,

   `category_name` varchar(255) NOT NULL,

  PRIMARY KEY (`category_id`)

  ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf-8
产品分类表

CREATE TABLE `product_to_category` (

  `product_id` int(11) unsigned NOT NULL,

  `category_id` int(11) unsigned NOT NULL,

  PRIMARY KEY (`product_id`,`category_id`)

  ) ENGINE=InnoDB DEFAULT CHARSET=utf-8

要获取产品价格区间统计上架的Shoes类别的产品,状态为在售\停售的数目

SELECT    

sum(CASE when product.product_price<10 then 1 else 0 end)   AS ‘(0,10)‘,    

sum(CASE when  product.product_price>=10 and  product.product_price<20 then 1 else 0 end)   AS ‘[10,20)‘,    

sum(CASE when  product.product_price>=20 and  product.product_price<30 then 1 else 0 end)   AS ‘[20,30)‘,    

sum(CASE when  product.product_price>=30 and  product.product_price<40 then 1 else 0 end)   AS ‘[30,40)‘,    

sum(CASE when  product.product_price>=40  then 1 else 0 end)   AS ‘[40,+)‘  

FROM test.product AS product 

LEFT JOIN test.product_to_category map ON product.product_id = map.product_id

LEFT JOIN test.category category ON map.category_id = category.category_id

 WHERE category.category_name = ‘Shoes‘ group by product.product_status;
技术分享

 

MYSQL分段统计