假设我有一些这样的数据
水果 | 价格 | 评分 |
---|---|---|
橙色 | 10 | 4 |
桃子 | 20 | 3 |
蓝莓 | 5 | 4 |
草莓 | 30 | 1 |
苹果 | 15 | 2 |
我想做的是,给定一种水果和一个价格范围,找到该水果在价格范围内的排名。
例如,让我们选择“橙色”和“$20”:
水果 | 价格 | 评分 | 评分百分比 |
---|---|---|---|
橙色 | 10 | 4 | 4/4=100% |
蓝莓 | 5 | 4 | 4/4=100% |
桃子 | 20 | 3 | 3/4 = 75% |
苹果 | 15 | 2 | 2/4 = 50% |
所以,在这种情况下我们可以看到水果<= $20 orange is one of the top rated, and is a good buy.
我已经做到了:
select max(rating) from fruits where price <= 20
但后来我不知道如何用它来计算评级百分比。我假设 sub 以某种形式选择......但我画了一个空白。
这也需要在 Sqlite 中工作。
一种方法可能是:
sqlite3 '' <<'EOD'
.headers on
.mode col
create table fruits (fruit,price,rating);
insert into fruits values
("orange", 10,4),
("peach", 20,3),
("blueberry", 5,4),
("strawberry",30,1),
("apple", 15,2)
;
select
t.*,
rating || "/" || m || " = " || (100*rating/m) || "%" as "rating percentage"
from
( select * from fruits where price<=20 ) t,
( select max(rating) as m from fruits where price<=20 )
order by rating desc
;
EOD
给予:
fruit price rating rating percentage
--------- ----- ------ -----------------
orange 10 4 4/4 = 100%
blueberry 5 4 4/4 = 100%
peach 20 3 3/4 = 75%
apple 15 2 2/4 = 50%