【问题标题】:SQL query to get all records with sum less than 10000SQL查询获取总和小于10000的所有记录
【发布时间】:2020-10-02 10:53:01
【问题描述】:

我的表格中的数据类似于以下数据集。

我想得到一组价格总和小于 10000 的物品。

CREATE TABLE Table1
(slno int, item varchar(10), price int);

INSERT INTO Table1
(slno, item, price)
VALUES
(1, 'item1', 1000),
(2, 'item2', 2000),
(3, 'item3', 3000),
(4, 'item4', 4000),
(5, 'item5', 5000),
(6, 'item6', 6000),
(7, 'item7', 10000),
(8, 'item8', 2000),
(9, 'item9', 8000),
(10, 'item10', 2500),
(11, 'item11', 9000),
(12, 'item12', 1000),
(13, 'item13', 2500),
(14, 'item14', 2500),
(15, 'item15', 2500);

我的 sql 查询如下所示:

SELECT slno, item,price
FROM
 (
 SELECT slno, item,price 
 (
SELECT SUM(price)
  FROM Table1
 WHERE slno<= t.slno
 ) total
  FROM Table1 t
 ) q
   WHERE total <= 1000
   ORDER BY item

但它没有给出预期的结果,它只给出了一组记录:

 (1, 'item1', 1000),
 (2, 'item2', 2000),
 (3, 'item3', 3000),
 (4, 'item4', 4000)

而我需要它来给我这样的东西:

 1ST SET

 (1, 'item1', 1000),
 (2, 'item2', 2000),
 (3, 'item3', 3000),
 (4, 'item4', 4000)

 2ND SET
 (7, 'item7', 10000),

@GordonLinoff

【问题讨论】:

标签: sql sql-server azure-sql-database


【解决方案1】:

这种类型的操作需要递归 CTE。在这种情况下,您可以使用这种逻辑为每一行分配一个组。以下假设 slno 没有您的示例数据中的空白:

with cte as (
      select slno, item, price, 1 as grp, price as running_price
      from table1
      where slno = 1
      union all
      select t1.slno, t1.item, t1.price,
             (case when t1.price + cte.running_price > 10000 then grp + 1 else grp end),
             (case when t1.price + cte.running_price > 10000 then t1.price else cte.running_price + t1.price end)
      from cte join
           table1 t1
           on t1.slno = cte.slno + 1
     )
select *
from cte
order by slno;

Here 是一个 dbfiddle。

【讨论】:

  • @DineshTripathi 该评论不可读。您应该更新您的问题(使用edit,或者以可消耗的格式提供它;也许通过小提琴。
  • @Gordon-Linoff 第 8 组的记录超过 total 大于 10000 。它应该只小于或等于 10000
  • @DineshTripathi 。 . .这会将数据分成不同的组,每组要么是总和小于 10,000 的行,要么由一行组成(不能更小)。这似乎是对您问题的合理解释。在示例中,第 8 组的总数为 7,500,小于 10,000。
猜你喜欢
  • 2014-03-16
  • 2022-12-05
  • 1970-01-01
  • 1970-01-01
  • 2020-07-07
  • 2017-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多