更新SQL查询逻辑

时间:2018-03-12 10:40:16

标签: sql azure-sql-database

我有一张如下表格

SELECT a.* FROM #testtable t
CROSS APPLY (
    VALUES (ID, OptionA, OptionACost, 1), (ID,OptionB, OptionBCost, 2),
           (ID, OptionC, OptionCCost, 3)
)a(Id, Name, Cost, ids)
ORDER BY a.ids, a.id

我需要编写更新查询来更新连续的手动计数列,如下所示。

TranId  SupplyType  SuppliedDate    ConsecutiveManualCount
1       A           05-Jan-12        0
2       A           05-Feb-12        0
3       M           07-Mar-12        0
4       M           07-Apr-12        0
5       A           08-May-12        0
6       M           07-Jun-12        0
7       M           08-Aug-12        0
8       M           06-Sep-12        0
9       A           07-Oct-12        0

逻辑类似于每个连续的手动供应类型“M”相应地更新计数。每当供应类型自动化时,SupplyType =“A”将计数重置为0.同时在计算计数时,应考虑提供的日期。对于TranId = 8,计数为2而不是3,因为2012年7月没有供应。

有人可以帮我查询相同内容。

1 个答案:

答案 0 :(得分:0)

您可以使用窗口功能执行此操作。以下使用lag()来确定组的开始时间,定义组的累积总和以及进行最终枚举的row_number()

select t.*,
       (case when supplyType = 'M'
             then row_number() over (partition by grp, supplyType order by tranid)
             else 0
        end) as ConsecutiveManualCount
from (select t.*, sum(isGroupStart) over (order by tranid) as grp
      from (select t.*,
                   (case when supplyType = 'A'
                         then 0
                         when lag(supplyType) over (order by tranid) = 'A'
                         then 1 
                         when datediff(day, lag(supplieddate) over (order by tranid), supplieddate) > 35
                         then 1
                         else 0
                    end) as isGroupStart
            from t
           ) t
     ) t;