MYSQL分段統計

來源:互聯網
上載者:User

標籤: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分段統計

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.