簡體   English   中英

SQL 服務器根據值計算連續的前行

[英]SQL Server Count Consecutive Preceding Rows based on Values

這對我來說是個很難寫出來的問題。

我有一個如下表:

日期 項目編號 標志A 標志B
2020-01-01 101 ñ
2020-01-02 101 ñ ñ
2020-01-03 101 ñ
2020-01-04 101 ñ
2020-01-05 101
2020-01-01 102 ñ
2020-01-02 102 ñ ñ
2020-01-03 102 ñ ñ
2020-01-04 102

我的目標是計算 FlagA = Y 的連續日期,包括每個 ItemNumber 的 FlagB = Y 的日期和之前的日期。 表中每個 ItemNumber 的最后日期將始終具有 FlagB = Y。

我試圖通過添加一個額外的列來實現這一點:

日期 項目編號 標志A 標志B 運行計數
2020-01-01 101 ñ 0
2020-01-02 101 ñ ñ 0
2020-01-03 101 ñ 1
2020-01-04 101 ñ 2
2020-01-05 101 3
2020-01-01 102 ñ 0
2020-01-02 102 ñ ñ 0
2020-01-03 102 ñ ñ 0
2020-01-04 102 1

我在 SQL Server 2012 上,但對 window 功能沒有很多經驗。 我嘗試了幾件事,包括:

COUNT(CASE WHEN [FLagB] = 'Y' THEN 1 ELSE 0 END) 
              over (partition by [ItemNumber],[FlagB] 
                   order by [Date] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS [RunningCount]

和:

COUNT(CASE WHEN [FLagB] = 'Y' THEN [ItemNumber] END) 
              over (PARTITION BY [ItemNumber] 
                   order by [Date] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS [RunningCount]

但這些都沒有得到正確的結果。

關於這個,go 可能有更好的方法 - 我不需要將新列添加到表中,我只需要一個提供每個 ItemNumber 計數的查詢。

任何建議將不勝感激。 先感謝您。

對於最近的不間斷序列,您似乎想要一個flagA = Y的枚舉。 那將是:

select t.*,
       (case when grp = 0 and flagA = 'Y'
             then row_number() over (partition by grp, flagA order by date) 
             else 0
        end) as runningCount
from (select t.*,
             sum(case when flagA = 'N' then 1 else 0 end) over (partition by itemNumber order by date desc) as grp
      from t
     ) t;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM