当另一个对应列为空时,过滤掉某些列

时间:2013-08-18 05:01:12

标签: mysql sql

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

我只想在AA,BB或CC不为空时从一行中选择A,B或C.

结束时会出现:

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

另一个例子:

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

另外一个例子,对于踢球:

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

感谢阅读!

以下是我根据您的帮助提出的解决方案,以防有人需要:

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;

1 个答案:

答案 0 :(得分:4)

你的意思是使用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