看到群里有人问了一道SQL查询的题,感觉比较有意义,就整理了个人想法并记录了下来
以下为对于该题目的一些想法,未必是正确答案,只是给出一种按照排名占比计算标签的思路。
use tysite;
CREATE TABLE `demo` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`category` varchar(45),
`name` varchar(45),
`figure` DOUBLE,
PRIMARY KEY (`id`)
) ENGINE=InnoDB CHARSET=utf8 COLLATE=utf8_bin;
insert into demo values
(null,'手机','华为 P30 pro',5488),
(null,'手机','苹果 iPhone X',6999),
(null,'手机','vivo NEX',3000),
(null,'手机','诺基亚 7920',538),
(null,'食品','蛋黄酥',10),
(null,'食品','吐司切片蛋糕',30),
(null,'食品','巧克力面包',6.5),
(null,'食品','曲奇饼干',28.5),
(null,'食品','燕麦手撕糕点',19.9);
统计脚本
SELECT (@rank := case when @parent_category = a.category then @rank + 1 else 1 end ) '本类排序',
a.category '分类',a.name '名称',a.figure '价格',a.all_num '本类总数',
@rank / a.all_num '排名占比',
CASE WHEN @rank / a.all_num < 0.3 THEN '高档'
WHEN ( @rank / a.all_num >= 0.3) && ( @rank / a.all_num <= 0.8) THEN '中档'
ELSE '低档' END '档次',
(@parent_category := a.category) parent_category
FROM (SELECT d.id,d.category,d.name,d.figure,t.all_num
FROM demo d
INNER JOIN (SELECT category,count(1) all_num FROM demo GROUP BY category) t ON t.category = d.category
ORDER BY d.category,d.figure DESC) a,
(SELECT @rank:=0, @parent_category :=null) b