Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute same query twice, but with single different WHERE clause

Tags:

sql

sql-server

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
like image 239
Dai Avatar asked Dec 20 '22 14:12

Dai


2 Answers

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
like image 93
VitaliyG Avatar answered May 03 '23 08:05

VitaliyG


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
like image 29
Serpiton Avatar answered May 03 '23 07:05

Serpiton