我一直在努力写一本书 mysql 查询。要求是计算 white 以及 red 项目,我可以购买的总价格为20美元。以下是我尝试的查询:
mysql
white
red
SELECT colour, purchasePriceFROM `product`
SELECT colour, purchasePrice
FROM `product`
它返回这个结果链接。但是,我想数一数 white 以及 red 物品的价格是20美元。例如,假设我有一个20美元的预算,每个项目的成本是2美元。因此,我知道我只能买10个。我希望这很容易理解。
8qgya5xd1#
对于mysql 8.0以后的版本,有一些窗口函数可以为允许的颜色创建累计价格:
select count(*) -- counts the number of itemsfrom(select sum(p1.purchasePrice) over (order by p1.purchasePrice asc) as c_price -- Our cumulative pricefrom product p1where colour in ('white', 'red') -- limit the colours) x2where x2.c_price <= 20 -- where the cumulative is less than the budget
select count(*) -- counts the number of items
from
(
select sum(p1.purchasePrice) over (order by p1.purchasePrice asc) as c_price -- Our cumulative price
from product p1
where colour in ('white', 'red') -- limit the colours
) x2
where x2.c_price <= 20 -- where the cumulative is less than the budget
编辑:似乎你是在寻找每件商品中你能买多少,而不是从列表中选择多少:
select colour, purchasePrice, floor(20/purchasePrice) as qty_for_20 -- floor rounds the number downfrom productswhere colour in ('white', 'red')
select colour, purchasePrice,
floor(20/purchasePrice) as qty_for_20 -- floor rounds the number down
from products
where colour in ('white', 'red')
1条答案
按热度按时间8qgya5xd1#
对于mysql 8.0以后的版本,有一些窗口函数可以为允许的颜色创建累计价格:
编辑:似乎你是在寻找每件商品中你能买多少,而不是从列表中选择多少: