I have a data table where there’s a list of columns (boiled down to the pertinent ones for this example):
users(
usr_pkey int identity(1, 1) primary key,
usr_name nvarchar(64),
...,
)
accounts(
acc_pkey int identity(1, 1) primary key,
usr_key int foreign_key references users(usr_pkey),
acc_effective datetime,
acc_expires datetime,
acc_active bit,
...,
)
From this table I’m looking to grab all records where:
- The account belongs to the specified user and
- In the first instance:
- the account is active and today’s date falls between the account’s effective and expiry date or
- In the second instance:
- if no records were identified by the first instance, the record with the most recent expiry date.
So – if an active record exists where today’s date falls between the account’s effective and expiry dates, I want that record. Only if no match was found do I want any account for this user having the most recent expiry date.
Here’s one solution I’ve found:
This would effectively order the records in the right priority sequence allowing me to pick the top one off the list
Strictly speaking, it doesn’t achieve exclusive or, but it could be applied to this data set to achieve the same end.