Excuse the simplicity of my question, I'm having a brain-fart:
Here's my table schema:
Foo( FooId, BarDate dateTime, Baz int )
Given this query
SELECT
    MAX( Foo.BarData )
FROM
    Foo
WHERE
    Foo.Baz = 2
    AND
    Foo.BarData < @dateParameter
There are cases where this query returns NULL because there are no rows that meet the criteria, in those situations I want the query to return the same value, except where Foo.Baz = 0.
I could do it with two subqueries, but it seems 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
                Just select both rows and limit result to 1 row, order so preferred row was first
SELECT TOP 1
  MAX( Foo.BarData )
FROM
  Foo
WHERE
  ((Foo.Baz = 2) OR
  (Foo.Baz = 0))
AND
  Foo.BarData < @dateParameter
GROUP BY Foo.Baz
ORDER BY Foo.Baz DESC
                        It's possible to get the MAX values for both Foo.Baz in the same query, using a CASE to separate the raw data
SELECT COALESCE(MAX(CASE WHEN Foo.Baz = 2 THEN Foo.BarDate ELSE NULL END)
              , MAX(CASE WHEN Foo.Baz = 0 THEN Foo.BarDate ELSE NULL END)
               )
FROM   Foo
WHERE  Foo.Baz IN (0,2)
  AND  Foo.BarDate < @dateParameter
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With