简体   繁体   English

使用LAG窗口函数按Oracle中的记录计算剩余总数

[英]Calculate Remaining Total by Record in Oracle Using LAG Window Function

I am having difficulty using the LAG window function to make what I can best describe as a ledger with a running total using Oracle 12. I have abstracted the problem like this: 我很难使用LAG窗口函数来做出最能描述的分类帐,而使用Oracle 12可以实现总帐。我已经将问题抽象为:

I have an airliner with a fixed number of seats, but sometimes the flight is oversold. 我有一架座机,座位数固定,但有时航班超卖了。 I am trying to figure out who gets a ticket and who doesn't by using a running total. 我试图通过运行总计来找出谁获得票证,而谁没有获得票证。

For each passenger (PASS), I have ordered the data by the class (1=1st class, 2=economy) and the priority (who ordered first) within it. 对于每位乘客(PASS),我已经按等级(1 = 1等级,2 =经济)和其中的优先级(先订购者)对数据进行了排序。

In the REM column, I am trying to get a running total of how many seats are left. 在“ REM”列中,我试图获取剩余的剩余席位总数。 I assume that each PASS will take up only one seat, and I have a fixed number of AVAIL seats per class. 我假设每个PASS仅占用一个座位,并且每个班级都有固定数量的AVAIL座位。 The seats remaining after that passenger is seated (REM) will decrease by one per user in the partition. 该乘客就座后剩余的座位(REM)将在分区中的每个用户减少一个。 The desired result would look like: 所需的结果如下所示:

PASS |PRI|CLASS|AVAIL|REM
User9 1   1     2     1
User1 4   1     2     0
User8 2   2     3     2
User4 3   2     3     1
User3 5   2     3     0
USER2 6   2     3     -1

I have been trying to do this: 我一直在尝试这样做:

SELECT 
    PASS, PRI, CLASS,
    LAG(AVAIL, 1, AVAIL) OVER (PARTITION BY CLASS ORDER BY CLASS, PRI) - 1 AS REM
FROM TABLE
ORDER BY CLASS, PRI

But my final data for REM has been coming out wrong: 但是我关于REM的最终数据出了错:

PASS |PRI|CLASS|AVAIL|REM
User9 1   1     2     1
User1 4   1     2     1
User8 2   2     3     2
User4 3   2     3     2
User3 5   2     3     2
USER2 6   2     3     2

I'm obviously approaching this wrong with my window function because it is looking for the next AVAIL record in the partition and subtracting one, but AVAIL doesn't change and so I get the same value for REM across the partition. 我显然用我的窗口函数来解决这个问题,因为它正在寻找分区中的下一个AVAIL记录并减去一个,但是AVAIL并没有改变,因此我在整个分区中获得相同的REM值。

How do I get REM to subtract 1 from AVAIL in the partition and then use that new value for AVAIL in the next row? 如何获得REM从分区中的AVAIL中减去1,然后在下一行中将新值用于AVAIL?

This seems to match your description: 这似乎符合您的描述:

AVAIL 
- Count(*)
  Over (PARTITION BY CLASS 
        ORDER BY PRI ROWS Unbounded Preceding)

Available seats minus the cumulative count of rows per class. 可用座位数减去每个班级的累积行数。

And a cumulative count is equal to a ROW_NUMBER: 累计计数等于ROW_NUMBER:

AVAIL 
- ROW_NUMBER()
  Over (PARTITION BY CLASS 
        ORDER BY PRI)

Just subtract the running sum from avail column. 只需从avail列中减去运行总和。

SELECT PASS, PRI, CLASS, AVAIL,
avail-sum(1) over(partition by class order by pri) AS REM
FROM TABLE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM