如何按小于 x 的总和对数据进行分组
How to group data by summed amount less than x
在 sql 中处理此问题时遇到问题。有 table 与客户相关的支票金额。如果我想给他们每个唯一的数字来支付,我不知道如何只用更新语句而不是逐行进行(有大量数据)
我必须按特定条件分组,然后付款,但不能超过 10000 美元。
Table
customer CheckAmount
a 4000
a 5000
a 2001
b 3333
c 8000
d 11000
我更新后它应该看起来像:
customer checkamount paymentnumber
a 4000 1
a 5000 1
a 2001 2
b 3333 3
c 8000 4
d 11000 5
仅在更新语句中这可能吗?
如果再有一个按时间标识交易的列就可以解决这个问题,像这样:
transaction_num customer checkamount
1 a 4000
2 a 5000
3 a 2001
4 b 3333
5 c 8000
6 d 11000
那么更新语句可以是这样的:
UPDATE p
SET p.paymentnumber = agg.new_paymentnumber
FROM payments p
JOIN (
SELECT *,
DENSE_RANK() OVER (
ORDER BY customer,
-- Only the first payments are not higher than 10,000:
/* CASE WHEN agg_sum <= 10000 THEN 0 ELSE agg_sum END */
-- All payments are within 10,000:
CEILING(agg_sum / 10000)
) AS new_paymentnumber
FROM (
SELECT *, SUM(checkamount) OVER (
PARTITION BY customer ORDER BY transaction_num
) AS agg_sum
FROM payments
) t
) agg ON p.transaction_num = agg.transaction_num
在 sql 中处理此问题时遇到问题。有 table 与客户相关的支票金额。如果我想给他们每个唯一的数字来支付,我不知道如何只用更新语句而不是逐行进行(有大量数据)
我必须按特定条件分组,然后付款,但不能超过 10000 美元。
Table
customer CheckAmount
a 4000
a 5000
a 2001
b 3333
c 8000
d 11000
我更新后它应该看起来像:
customer checkamount paymentnumber
a 4000 1
a 5000 1
a 2001 2
b 3333 3
c 8000 4
d 11000 5
仅在更新语句中这可能吗?
如果再有一个按时间标识交易的列就可以解决这个问题,像这样:
transaction_num customer checkamount
1 a 4000
2 a 5000
3 a 2001
4 b 3333
5 c 8000
6 d 11000
那么更新语句可以是这样的:
UPDATE p
SET p.paymentnumber = agg.new_paymentnumber
FROM payments p
JOIN (
SELECT *,
DENSE_RANK() OVER (
ORDER BY customer,
-- Only the first payments are not higher than 10,000:
/* CASE WHEN agg_sum <= 10000 THEN 0 ELSE agg_sum END */
-- All payments are within 10,000:
CEILING(agg_sum / 10000)
) AS new_paymentnumber
FROM (
SELECT *, SUM(checkamount) OVER (
PARTITION BY customer ORDER BY transaction_num
) AS agg_sum
FROM payments
) t
) agg ON p.transaction_num = agg.transaction_num