码迷,mamicode.com
首页 > 数据库 > 详细

MYSQL分段统计

时间:2017-06-29 19:22:14      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:category   prim   unsigned   技术   from   cas   rod   creat   int   

产品表

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分段统计

标签:category   prim   unsigned   技术   from   cas   rod   creat   int   

原文地址:http://www.cnblogs.com/huixuexidezhu/p/7095713.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!