I'm trying to select two columns from a join with three tables. Specifically, the first column is a rate which is computed as a subtraction between two columns if another column equals 1. The second column is a flag for how many times the txn_rate is not null. Am I doing the 'case when' statements in the most efficient way possible? Please see the code below (I masked the join logic to be simpler, since I don't think that matters too much)
One quick note: the logic I wanted to follow was create a flag and then sum the flag in a staging table (this is pre-staging). Is there a more efficient way to create a binary flag?
Select case when a.column = 1 then (b.column - c.column) else null end as txn_rate,
case when (case when a.column = 1 then (b.column - c.column) else null end) is not null then 1
else null end as txn_rate_flag
FROM table1 a
Left Join table2 b
ON a.ID = b.ID
Left Join table3 c
ON a.ID2 = c.ID2
I would write the following
case when (case when a.column = 1 then (b.column - c.column) else null end) is not null then 1
else null end as txn_rate_flag
as case when a.column = 1 and (b.column - c.column) is not null then 1 else null as txn_rate_flag