This is difficult question for me to write out.
I have a table like below:
Date | ItemNumber | FlagA | FlagB |
---|---|---|---|
2020-01-01 | 101 | Y | N |
2020-01-02 | 101 | N | N |
2020-01-03 | 101 | Y | N |
2020-01-04 | 101 | Y | N |
2020-01-05 | 101 | Y | Y |
2020-01-01 | 102 | Y | N |
2020-01-02 | 102 | N | N |
2020-01-03 | 102 | N | N |
2020-01-04 | 102 | Y | Y |
My goal is to count the consecutive dates where FlagA = Y including and preceding the date where FlagB = Y for each ItemNumber. The last date for each ItemNumber in the table will always have FlagB = Y.
I'm trying to achieve this by adding an additional column:
Date | ItemNumber | FlagA | FlagB | RunningCount |
---|---|---|---|---|
2020-01-01 | 101 | Y | N | 0 |
2020-01-02 | 101 | N | N | 0 |
2020-01-03 | 101 | Y | N | 1 |
2020-01-04 | 101 | Y | N | 2 |
2020-01-05 | 101 | Y | Y | 3 |
2020-01-01 | 102 | Y | N | 0 |
2020-01-02 | 102 | N | N | 0 |
2020-01-03 | 102 | N | N | 0 |
2020-01-04 | 102 | Y | Y | 1 |
I'm on SQL Server 2012 but do not have a lot of experience with window functions. I've tried several things including:
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]
and:
COUNT(CASE WHEN [FLagB] = 'Y' THEN [ItemNumber] END)
over (PARTITION BY [ItemNumber]
order by [Date] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS [RunningCount]
but these haven't gotten correct results.
There may be a better way to go about this - I don't need to add the new column to the table, I only need a query that provides the count for each ItemNumber.
Any advice would be greatly appreciated. Thank you in advance.
You seem to want an enumeration of flagA = Y
for the most recent uninterrupted sequence. That would be:
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.