lundi 27 avril 2015

SQL function-like WHERE statement

I've researched for a pretty long time and extensively already on this problem; so far nothing similar has come up.

Here's my problem below.

I'm trying to create a SELECT statement in SQLite with conditional filtering that works somewhat like a function. Sample pseudo-code below:

SELECT col_date, col_hour FROM table1 JOIN table2 
ON table1.col_date = table2_col_date AND table1.col_hour = table2.col_hour
    WHERE
        IF table2.col_name = "a" THEN {filter these records further such that its col_volume >= 600} AND
        IF table2.col_name = "b" THEN {filter these records further such that its col_volume >= 550}
        {if any of these two conditions are not met, do not get any of the col_date, col_hour}

*I know SQLite does not support the IF statement but this is just to demonstrate my intention.

Here's what I've been doing so far. According to this article, it is possible to transform CASE clauses into boolean logic, such that you will see here:

SELECT table1.col_date, table1.col_hour FROM table1 INNER JOIN table2 
ON table1.col_date = table2.col_date AND table1.col_hour = table2.col_hour
    WHERE
        ((NOT table2.col_name = "a") OR table2.col_volume >= 600) AND
        ((NOT table2.col_name = "b") OR table2.col_volume >= 550)

In this syntax, the problem is that I still get col_dates and col_hours where at least one col_name's col_volume for that specific col_date and col_hour did not meet its requirement. (e.g. I still get a record entry with col_date = 2010-12-31 and col_hour = 5, but col_name = "a"'s col_volume = 200 while col_name = "b"'s col_volume = 900. This said date and hour should not appear because "a" has a volume which is not >= 600, even though "b" met its volume requirement which is >= 550.)

Aucun commentaire:

Enregistrer un commentaire