0

我有一个连接两个表并给出结果的查询:

A.ID    A.SelectedField B.ID    B.Field1    B.Field2    B.Field3 
1           Field1           1    **0**          20           30
2           Field2           2    11             **21**        0 
3           Field3           3    12             22           **0** 
4           Field3           4    13             0            **33**

而且我只需要检索所选字段不为 0 的行,因此我想要的结果是:

A.ID    A.SelectedField B.ID    B.Field1    B.Field2    B.Field3 
2            Field2          2    11             21           0 
4            Field3          4    13             0            33 

我怎么做?

4

2 回答 2

1

像这样的东西应该工作:

WHERE 
 CASE A.SelectedField WHEN 'Field1' THEN B.Field1
                      WHEN 'Field2' THEN B.Field2
                      WHEN 'Field3' THEN B.Field3
                      ELSE 0 -- default value
 END <> 0

SQLFiddle 演示

于 2013-10-14T12:35:18.953 回答
0
SELECT CASE WHEN A.SelectedField = 'Field1' AND  B.Field1 <> 0 THEN  A.SelectedField 
            WHEN A.SelectedField = 'Field2' AND  B.Field2 <> 0 THEN  A.SelectedField        
            WHEN A.SelectedField = 'Field3' AND  B.Field3 <> 0 THEN  A.SelectedField 
            ELSE NULL
        END
于 2013-10-14T12:35:45.223 回答