Skip to content
Advertisement

Is there a way to look at the previous evaluation within a CASE expression?

I’ve created the following table in Excel as an example. I would like to do a similar expression (like the formula shown in Excel) in SQL Server on a similar looking table. The columns row_num and switch were already created based on previous CASE statements.

Click for Excel sheet

Is there any way to achieve this?

Thanks for having a look!

PS: in case image does not work:

Advertisement

Answer

You want a cumulative sum of the cases when switch = 0.

However, SQL tables represent unordered sets. So you need a column (or multiple columns) that specify the ordering. In your example, you can use the excel row number, but your data might have a more appropriate column.

Hence:

If switch only takes on two values, you can simplify this to:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement