Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: Conditional Select within Conditional Select

Tags:

sql

select

Please bear with me on this, this is quite difficult to explain and I am not sure if I am using the correct terminology.

I need to do a rather complicated select. It is effectively a select statement which conditionally decides what field to use to filter the select. If a certain date field is not null, I need to check that the value in that field is within a certain range. Otherwise if that date field is null I need to check another field, int field, on the same table is within a certain range:

Pseudocode:

If [Date] is not null
    Get sum (table.value) for rows Date >= dateValue and Date < dateValue
Else
    Get sum (table.value) for rows Int >= intValue and Int < intValue

My current attempt:

SELECT CASE WHEN a.Date IS NOT NULL THEN 
(SUM(CASE WHEN (a.Date >= cal.Date) THEN ABS(a.Value) ELSE 0 END)) 
ELSE 
(SUM(CASE WHEN (b.Days >= 0) THEN ABS(a.Value) ELSE 0 END) 
END AS 'A'

Any ideas? Ask if you need more information. Thanks in advance.

like image 736
Damien Avatar asked Nov 02 '10 20:11

Damien


2 Answers

One way is to have 2 separate queries UNIONed together, but only one clause will produce a value. This avoids having OR statements.

SELECT SUM(Value)
FROM MyTable
WHERE MyTable.Date >= dateValue and Table.Date < dateValue  --NULL Date = false always
UNION ALL
SELECT SUM(Value)
FROM MyTable
WHERE MyTable.Int >= intValue and Table.Int < intValue
    AND --ignore this clause if date is NOT NULL
    MyTable.Date IS NULL

Edit, with OR:

SELECT SUM(Value)
FROM MyTable
WHERE
     (
      MyTable.Date IS NOT NULL AND 
      MyTable.Date >= dateValue and Table.Date < dateValue
      )
      OR --actually mutually exclusive
     (
      MyTable.Date IS NULL AND 
      MyTable.Int >= intValue and Table.Int < intValue 
      )
like image 61
gbn Avatar answered Sep 28 '22 17:09

gbn


This works and isn't all that far off from the pseudocode, as long as I'm interpreting what you want to do correctly.

SELECT  SUM(Value)
FROM    T
WHERE
        CASE WHEN DateValue IS NOT NULL 
                THEN DateValue BETWEEN FromDate AND ToDate
                ELSE IntValue BETWEEN FromInt AND ToInt
                END 
like image 37
Samuel Neff Avatar answered Sep 28 '22 19:09

Samuel Neff