【问题标题】:How can I count items from purchase price?如何从采购价格中计算商品?
【发布时间】:2019-04-30 14:41:23
【问题描述】:

我一直在尝试编写 mysql 查询。要求是计算whitered 项目的数量,我可以以总共 20 美元的价格购买这些项目。这是我尝试的查询:

SELECT colour, purchasePrice
FROM `product`

它返回这个结果link。 但是,我想计算 20 美元的价格中有多少 whitered 商品。例如,假设我的预算为 20 美元,每件商品的价格为 2.00 美元。因此,我知道我只能购买其中的 10 个。 我希望这很容易理解。

【问题讨论】:

  • 请提供样本数据和期望的结果。
  • 红色和白色有多个价格,您总是以最低价购买吗?
  • 请标记您使用的 MySQL 版本
  • @GordonLinoff 感谢您的回复,如果我与20 budget 核对,那么对于白色项目的预期输出可能是这样的White 10 items
  • @P.Salmon 我想计算预算中的项目数

标签: mysql sql database mysql-workbench


【解决方案1】:

对于 MySQL 8.0 及更高版本,有窗口函数可以为允许的颜色创建累积价格:

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 down
from products
where colour in ('white', 'red')

【讨论】:

  • select colour, purchasePrice, floor(purchasePrice / 20) as qty_for_20 -- floor rounds the number down from products where colour in ('white', ' red')给我EMPTY记录
  • @icon 看起来您使用的是早期版本。空行应该由我的编辑修复。
  • thankssssssssssssssssssssssss 工作得很好:) @JohnHC
猜你喜欢
  • 1970-01-01
  • 2021-04-17
  • 2023-01-12
  • 2019-02-02
  • 1970-01-01
  • 2019-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多