我正在try 对以下Customer_Item视图进行一些处理

CustomerId Amount ItemId ItemPrice IsActiveStore Priority
1 1000 1 100 1 1
1 1000 2 200 1 2
1 1000 3 300 0 3
2 5000 4 1000 1 1
2 5000 5 4000 1 2
2 5000 6 500 1 3

For each customer, I want to subtract the prices of the related items, that are ordered by priority, from his amount, and update the status for each item accordingly
In case IsActiveStore is false or the amount reaches zero, then skip the item

备注:

  • 优先级不是连续的,而是按顺序排列的,项目ID 1、2和3的优先级可以分别为5、7和9
  • 如果按优先级排序的第一个项目的价格超过客户数量(例如5k),则将跳过该项目,并继续处理其余优先级

因此,更新后的Customer表应该如下所示

CustomerId Amount
1 700
2 0

更新后的Items表如下

ItemId ItemStatus
1 subtracted
2 subtracted
3 skipped
4 subtracted
5 subtracted
6 skipped

现在,我用一个游标在客户上循环,对于每个客户,我使用另一个游标在相关项目上循环,这很有效,但对于 Big Data 来说,它需要很长时间.

Is there any faster alternative to do the same processing efficiently?
Thanks in advance.

推荐答案

您可以创建一个包含累计总和的扩展视图,并将其用于两个查询:

CREATE View Customer_Item_Extended as
    select *
    , ( select sum(ItemPrice * isActiveStore)
        from Customer_Item
        where CustomerId = civ.CustomerId
            and ItemPrice <= Amount
            and [Priority] <= civ.[Priority]) SumPrices
    from Customer_Item civ

这可能是使用该扩展视图的一种方式:

-- Customer table to update
select CustomerId
    ,  Amount - Max(SumPrices) as NewAmount
from   Customer_Item_Extended
where  SumPrices <= Amount
group by CustomerId, Amount

-- Items table to update
select ItemId
    ,  case when SumPrices > Amount
                or ItemPrice > Amount
                or isActiveStore = 0
        then 'skipped' else 'subtracted'
       end as NewItemStatus
from   Customer_Item_Extended

db<>fiddle

Sql相关问答推荐

在SQL中向每个子字节组添加字节行

如何解决Error:operator is not unique:unknown—unknown在一个动态SQL查询?""""

从2个表中查找每条记录的唯一最接近的日期匹配

Postgres JSONB对象筛选

Ffltter&;Dart SQL Lite包:是否可以在一个查询中执行多条更新语句(每次执行不同的WHERE参数)

更新其组的日期字段值小于最大日期减go 天数的记录

如何在SQL Server中拆分包含字符和数字的列?

返回找到的最小和最大row_number()spark SQL

从包含PostgreSQL中的JSON值的列中提取列表或目录

如何使用SQL Server中的Nodes()方法执行与OPENXML相同的操作

如何使用不重复的单个顶级字段(列)向json数组 Select 多行

用VB.NET在Dapper中实现MS Access数据库顺序透视

更正用于判断错误组合的SQL

Postgres SQL查询从字符串中获取邮箱地址

连续天跟踪购买情况(将标记返回到另一列?)

如何从三个连接表中获取数据,并始终显示第一个表中的数据,以及第三个表中的空值或现有记录?

达到特定值时,从0开始累加求和

SQL 函数 DIFFERENCE 返回有趣的分数

奇怪的甲骨文行为

REGEXP 用于字符串格式化以对用空格分隔的字符和数字进行分组