根据商品类型按商品价格对商品打标签。标签规则:前20%为高档,20%到80%为中档,后20%为低档。

考点:窗口函数与case when

题目:根据商品类型按商品价格对商品打标签。标签规则:前20%为高档,20%到80%为中档,后20%为低档。

题目

1.建表:

CREATE TABLE IF NOT EXISTS `goods_1`(
   `id` INT UNSIGNED AUTO_INCREMENT,
   `goods_type` VARCHAR(10) NOT NULL,
   `goods_name` VARCHAR(10) NOT NULL,
   `goods_price` INT NOT NULL,
   PRIMARY KEY ( `id` )
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

2.插入数据:

insert into goods_1 (goods_type, goods_name, goods_price) values('手机','华为','5999');
insert into goods_1 (goods_type, goods_name, goods_price) values('手机','苹果','6999');
insert into goods_1 (goods_type, goods_name, goods_price) values('手机','vivo','3999');
insert into goods_1 (goods_type, goods_name, goods_price) values('手机','小米','4999');
insert into goods_1 (goods_type, goods_name, goods_price) values('手机','oppo','3999');
insert into goods_1 (goods_type, goods_name, goods_price) values('食品','好多鱼','5');
insert into goods_1 (goods_type, goods_name, goods_price) values('食品','牛肉干','20');
insert into goods_1 (goods_type, goods_name, goods_price) values('食品','巧克力','15');
insert into goods_1 (goods_type, goods_name, goods_price) values('食品','奥利奥','8');
insert into goods_1 (goods_type, goods_name, goods_price) values('食品','可乐','3');

3.查询数据:

SELECT t1.*, 
			 CASE WHEN t1.row_num/t1.type_num <=0.2 then "高档" 
			 WHEN 0.8 <= t1.row_num/t1.type_num then "低档"
			 else "中档"
			 END as goods_level
FROM(
		SELECT goods_type,
					 goods_name,
					 goods_price,
					 ROW_NUMBER() over(PARTITION BY goods_type ORDER BY goods_price DESC) row_num, 
					 count(*) over(PARTITION BY goods_type) type_num
		FROM goods_1)t1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值