Sorry the simplicity of my question, I have a brain navel:
Here is my table layout:
Foo( FooId, BarDate dateTime, Baz int )
Given this request
SELECT
MAX( Foo.BarData )
FROM
Foo
WHERE
Foo.Baz = 2
AND
Foo.BarData < @dateParameter
There are cases when this query returns NULL, because there are no rows matching the criteria, in those situations I want the query to return the same value, except when Foo.Baz = 0.
I could do this with two subqueries, but it seems to be a hack. Isn't there a better way?
SELECT
COALESCE( Attempt1.BarData, Attempt2.BarData )
FROM
(
SELECT
MAX( Foo.BarData ) As BarData
FROM
Foo
WHERE
Foo.Baz = 2
AND
Foo.BarData < @dateParameter
) As Attempt1
OUTER JOIN
(
SELECT
MAX( Foo.BarData ) As BarData
FROM
Foo
WHERE
Foo.Baz = 0
AND
Foo.BarData < @dateParameter
) As Attempt2 ON 1 = 1
source
share