Skip to content
Advertisement

SQL to return 1 for each row with column range in 2017 or 2018 or 2019

I have a query that looks like this:

The returned data looks like this sort of thing (ignore the 2018 column for now):

How do I add a column, say [2018], and put a 1 for if status_from_date to status_thru_date is in 2018, or a 0 if not?

I wanted to add the following at the –(a) in the query:

This doesn’t seem to be working, though. See the 2018 column in the above table. It’s showing 1 for all returned, and it’s not excluding nulls. It’s pretty complicated. status_from and status_thru could fall with 2018 in it, or 2018 could be inside status_from and status_thru, which should both be 1.

How do I exclude the nulls, and how do I show a 1 when the status date includes 2018?

I’ve looked at range within range, and return 0 or 1. I don’t think I have all cases since the ranges overlap as well.

**Update: I tried adding this at –(a) above instead, per the potential answer below:

but I’m getting Ambiguous column name ‘status_from_date’. Ambiguous column name ‘status_thru_date’. Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.

Any ideas? Figured it out.

**Update 2: How about this?

That one is putting a 1 in the 2017 column for both male and female for the data of: status_from: 2014-10-01 and status_to: 2016-09-30

Advertisement

Answer

You could do something like this:

while would be to check if start or end contains 2018, or if the date is between start and thru

which produces:

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