Skip to content
Advertisement

SQL Server => How to use “case when” on multiple column to show a formula result based on a condition in the same line

I’m trying to provide an overall result of a formula ([CALCULATION]) and then in two extra columns ([NO_TENURE] & [TENURE]) the same calculation but using “CASE WHEN” to filter the information based on another column called [TENURE], everything in one single line like this:

Right now is being shown this way:

This is the code I’m using:

I really appreciate the help!

Advertisement

Answer

You have TENURE in your GROUP BY, which means that each different tenure in your source data will get a different row in the output.

If you take TENURE out of there, you’ll get the one row you want. The your CASE expression won’t work, because it should be INSIDE the aggregate functions…

The next question is how to avoid the massive repetition. That’s done by using sub-queries, CTEs or applied functions, to define expressions in one scope and use them in a different scope.

I’m on a phone, so that will take me a few minutes, but I’ll add it shortly.

The ELSE -1 is only there incase some rows have a NULL for the TENURE.

Demo : db<>fiddle

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