【问题标题】:SSMS Expand to Multiple Rows based off of EvaluationSSMS 根据评估扩展到多行
【发布时间】:2018-09-21 16:27:41
【问题描述】:

第一次发帖。我试图搜索类似的场景,但我什至不知道我正在尝试的正确术语。

关于这个问题。我有一个带有数量列的 CTE 数据集。使用此列,我需要根据以一定成本保存数量的价格层表进行评估。我需要生成一个销售价格层表中的单位的输出,并使用 FIFO 方法确定正确的成本。下面可能会更好地说明这一点。

CTE(简体):

ITEMNMBR    QTY
00378       1000

价格层表(最旧在顶部,最新在底部):

ITEMNMBR    QTYREC    QTYSOLD    UNITCOST
00378       500       125        0.45
00378       250       0          0.55
00378       1000      0          0.75

预期结果: 根据 CTE 的数量,我想先逐步售出最旧的价格层,一直持续到完成数量为止。

ITEMNMBR    QTY    UNITCOST    TOTALCOST
00378       375    0.45        168.75
00378       250    0.55        137.50
00378       375    0.75        281.25          //This leaves the last price layer with 625 units remaining.

更简单的例子:

CTE(简体):

ITEMNMBR    QTY
05583       250

价格层表(最旧在顶部,最新在底部):

ITEMNMBR    QTYREC    QTYSOLD    UNITCOST
05583       500       125        0.2
05583       250       0          0.3
05583       1000      0          0.4

预期结果:

ITEMNMBR    QTY    UNITCOST    TOTALCOST
05583       250    0.2         50     //Leaves 125 units in the first price layer

我什至不一定要寻找解决方案,只是寻找正确方向的一点。

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    我能够通过一些努力解决这个问题。使用嵌套游标和临时表,我能够获得所需的行为。

    伪代码:

    ;declare sales_cursor cursor for WITH CTEDateset as (/*CTE Code here*/)
    
    Iterate through every record in sales_cursor
    
    For each record, declare an inner cursor
    declare price_cursor cursor for select * from price_layer_table
        For each price layer record, perform math 
            Check if the total quantity fits in a single layer 
                  If so add a new record to the temp table and exit out of the inner cursor. 
                  If not, subtract the available amount and add a record to the temp table, continue to next price layer with the remaining amount
    
    select * from tempSales
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多