【问题标题】:Maximum number of products for given amount from the product list in SQL server without using While/Cursor?在不使用 While/Cursor 的情况下,SQL Server 中产品列表中给定数量的产品的最大数量?
【发布时间】:2022-11-30 23:16:07
【问题描述】:

我有一张名为 '产品'

Create table products(ProductName VARCHAR(100), Price INT, Quantity INT)

Insert into products values ('Pencil',3,20)
Insert into products values ('Rubber',4,5)
Insert into products values ('Scale',4,15)

ProductName  Price       Quantity
------------------------ -----------
Pencil       3           20
Rubber       4           5
Scale        4           15

这是要求。

最多花费 100 美元最多可以购买多少件商品?

我只需要输出值作为26. (20 支铅笔 + 5 橡皮 + 1 个刻度)

我不需要项目列表,我只需要尽可能多的产品。

如果表格只有以下值

ProductName  Price       Quantity
------------ ----------- -----------
Book         90          2
Note         120         4

我只需要返回1个(不能购买超过 1 本书的产品)

这需要在T-SQL中实现。我们不允许使用WHILECURSOR

【问题讨论】:

  • 您至少有一个要实现的算法吗?您看过递归公用表表达式 (CTE) 吗?
  • SQL Server <> SQLite,SQLite 不使用 T-SQL;你在这里实际使用什么?
  • 老实说,这个问题作为使用 T-SQL 解决的问题也没有任何意义。
  • 如果你选择购买 20 支铅笔 + 1 橡皮 + 9 秤 = 30 件,你会选择 26 件还是 30 件
  • 我已经继续并暂时删除了冲突的标签,因为 OP 尚未阐明他们使用的是什么。他们需要edit他们的问题才能(重新)添加适当的标签。

标签: sql


【解决方案1】:

也许运行总计可以在这里提供帮助:

declare @products table (ProductName VARCHAR(100), Price INT, Quantity INT)

Insert into @products values ('Pencil',5,20)
Insert into @products values ('Rubber',30,5)
Insert into @products values ('Scale', 80,15)
Insert into @products values ('Book', 10,15)

select SUM(Quantity)
from
(
    select 
        *,
        SUM (Price) OVER (order by price rows unbounded preceding) AS RunningTotal
    from @products
) tbl
where RunningTotal <= 100

【讨论】:

    猜你喜欢
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多