Skip to content
Advertisement

SQL query – not null

I have sql query:

Select id
    ,MAX(CASE WHEN (pos = "10") THEN date ELSE NULL END) position10
    ,MAX(CASE WHEN (pos = "18") THEN date ELSE NULL END) position18
    ,MAX(CASE WHEN (pos = "20") THEN date ELSE NULL END) position20
    
FROM table
WHERE 
date BETWEEN "${od=2021-05-01 00:00:01}" AND "${do=2021-07-01 00:00:01}"
AND pos IN('10','18','20')
group by id

I got this table

id position10 position20 position30
1 2021-05-02 2021-05-02 2021-05-3
2 2021-05-15 2021-05-16 2021-05-18
3 2021-07-08 NULL NULL

And I want lines where NULL values are not picked up. A try this:

SELECT * FROM (
Select id
        ,MAX(CASE WHEN (pos = "10") THEN date ELSE NULL END) position10
        ,MAX(CASE WHEN (pos = "18") THEN date ELSE NULL END) position18
        ,MAX(CASE WHEN (pos = "20") THEN date ELSE NULL END) position20
        
    FROM table
    WHERE 
    date BETWEEN "${od=2021-05-01 00:00:01}" AND "${do=2021-07-01 00:00:01}"
    AND pos IN('10','18','20')
    group by id )T 
WHERE (position10 IS NOT NULL)
       OR (position18 IS NOT NULL)
       OR (position20 IS NOT NULL)

But it still chooses to me where the NULL value appears somewhere.

Advertisement

Answer

You need to change OR to AND in WHERE clause

SELECT * FROM (
Select id
        ,MAX(CASE WHEN (pos = "10") THEN date ELSE NULL END) position10
        ,MAX(CASE WHEN (pos = "18") THEN date ELSE NULL END) position18
        ,MAX(CASE WHEN (pos = "20") THEN date ELSE NULL END) position20
        
    FROM table
    WHERE 
    date BETWEEN "${od=2021-05-01 00:00:01}" AND "${do=2021-07-01 00:00:01}"
    AND pos IN('10','18','20')
    group by id )T 
WHERE position10 IS NOT NULL
       AND position18 IS NOT NULL
       AND position20 IS NOT NULL
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement