Hello again,
Code:
DROP TABLE IF EXISTS temp_codes;
CREATE TABLE temp_codes (end_year INT(4), code_value INT(1));
INSERT INTO temp_codes VALUES (1990,1),(1991,2),(1992,3),(1994,4),(1998,5),(2005,6),(null,7);
I have this table that keeps code values eligible until certain times. If the field end_year IS NULL, that means the record is alive or eligible for the current time.
The SQL statement for retrieving the current code value is:
Code:
SELECT code_value
FROM temp_codes
WHERE end_year IS NULL;
For historical values, take Year 1993 e.g., the relevant value is retrieved by looking for the least upper bound of 1993:
Code:
SELECT code_value
FROM temp_codes T1
WHERE end_year = (SELECT MIN(end_year)
FROM temp_codes T2
WHERE T2.end_year >= 1993);
I am having trouble combining the two conditions in the WHERE clause to create a SELECT statement that works regardless of the current / historical distinction of the input year.
Using the CASE construction looked promising but all formulations I tried just keep failing. Among them is the following that tries to find a value on the assumption that the input year is historical then, if this fails, look for the current one.
Code:
SELECT code_value
FROM temp_codes T1
WHERE end_year CASE WHEN EXISTS (SELECT * FROM temp_codes T2 WHERE end_year >= 1993)
THEN (SELECT MIN(end_year) FROM temp_codes T2 WHERE end_year >= 1993)
ELSE NULL END;
TIA
Ik
