Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filter out certain columns when another corresponding column is null

Tags:

sql

mysql

Name    A       B        C         AA   BB  cc
--------------------------------------------------------
Name1   Data1   n       Data3       3   n   15
Name2   n       Data2   Data4       n   2   8

I want to select A, B, or C from a row only if AA, BB, or CC is not null.

So the end would appear:

select Name, A,B,c from table where ??? AA<10 and BB<10 and CC<10
^I know this is dumb, just to help you understand my goal.

Name   A      B      C
-------------------------
Name1 Data1
Name2        Data2 Data4

Another example:

select Name, A,B,c from table where ??? AA<5 and BB<5 and CC<5
^I know this is dumb, just to help you understand my goal.

Name   A      B      C
-------------------------
Name1 Data1
Name2        Data2

One more example, for kicks:

select Name, A,B,c from table where ??? AA<3 and BB<3 and CC<3
^I know this is dumb, just to help you understand my goal.

Name   A      B      C
-------------------------
Name2        Data2

Thanks for reading!

Here's the solution I came up with based on your help, in case anyone needs it:

SELECT `Name`,
CASE
    WHEN SIGN(`AA`)>0
    THEN `A`
END A,
CASE
    WHEN SIGN(`BB`)>0
    THEN `B`
END B,
CASE
    WHEN SIGN(`CC`)>0
    THEN `C`
END C,
FROM TABLE;
like image 272
hogarth45 Avatar asked Mar 27 '26 21:03

hogarth45


1 Answers

you mean like using IS NOT NULL:

select Name, A,B,c from table where 
    AA IS NOT NULL AND BB IS NOT NULL 
    AND CC IS NOT NULL

OR

SELECT Name, 
CASE WHEN AA IS NOT NULL 
    THEN A ELSE NULL AS acol,
CASE WHEN BB IS NOT NULL
    THEN B ELSE NULL AS bcol,
CASE WHEN CC IS NOT NULL
    THEN C ELSE NULL AS ccol
FROM table WHERE your_other_conditions
like image 79
Sudhir Bastakoti Avatar answered Mar 29 '26 10:03

Sudhir Bastakoti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!