在具有两列的where子句中使用case语句

时间:2017-06-11 16:14:24

标签: sql sql-server tsql

在应用以下条件时,如何过滤下表中的行的任何建议/想法都会很棒。提前致谢

条件1:Effective_date是08/01/2017或之前,当UABP为NULL时,我需要所有ID /空白/任何非零值/零

条件2:Effective_date > 08/01/2017时,我需要应用过滤器并仅选择具有UABP > 0的ID并省略其他记录。

初始查询:

注意:我在结果表中包含UABP和Eff_date列以显示其数据的概念,但我不想在查询中使用它们

SELECT 
    MAX(id_num) [ID], Submission_Num 
FROM 
    [Fiduciary] 
GROUP BY 
    Submission_Num

修改后的查询但无法获得预期结果:

--edited corrected one for fidicuary standalone when effective date greater than 08/01
SELECT 
    MAX(id_num) [ID], Submission_Num 
FROM 
    [Fiduciary] 
WHERE
    UABP <> '' OR UABP IS NOT NULL OR UABP <> 0 
    AND  Effective_Date >  '08/1/2017'
GROUP BY 
    Submission_Num

原始表

+---+--------------------+-------------+-----------------+
|ID |    Submission_Num  | UABP        | Effective_date  |
+---+--------------------+-------------+-----------------+
| 1 | 12121121           | NULL        |  07/1/2017      | 
| 2 | 65662656           | 565         |  06/1/2017      |   
| 6 | 24646426           |             |  05/1/2017      |    
| 3 | 12652354           | 0           |  06/1/2017      |      
| 8 | 56566565           | 232         |  08/02/2017     |   
| 9 | 65665656           | NULL        |  08/02/2017     | 
| 10| 76358928           | 0           |  09/02/2017     | 
+---+--------------------+-------------+---------------- +

预期结果:

+---+--------------------+-------------+-----------------+
|ID |    Submission_Num  | UABP        | Effective_date  |
+---+--------------------+-------------+-----------------+
| 1 | 12121121           | NULL        |  07/1/2017      | 
| 2 | 65662656           | 565         |  06/1/2017      |   
| 6 | 24646426           |             |  05/1/2017      |    
| 3 | 12652354           | 0           |  06/1/2017      |      
| 8 | 56566565           | 232         |  08/02/2017     |   
+---+--------------------+-------------+---------------- +

3 个答案:

答案 0 :(得分:1)

根据您的问题,我认为我的标准是正确的,但我并没有完全遵循您的UABP为零或不为零,因此您可能需要更改该标准以适合您的解决方案。

SELECT Max(id_num) [ID], Submission_Num FROM [Fiduciary] 
WHERE Effective_Date <= '08/1/2017' AND UABP = '' 
   OR Effective_Date <= '08/1/2017' AND UABP IS NULL 
   OR Effective_Date <= '08/1/2017' AND UABP >= 0 
OR    Effective_Date > '08/1/2017' AND UABP > 0
GROUP BY Submission_Num
ORDER BY Submission_Num

重点是,我将其分解为多组OR / AND语句。

答案 1 :(得分:0)

就这样做

SELECT Max(id_num) [ID], Submission_Num FROM [Fiduciary] 
where Effective_Date <= '08/1/2017' or Effective_Date >  '08/1/2017' and UABP>0
GROUP BY Submission_Num

答案 2 :(得分:0)

我会将查询写成:

SELECT Max(id_num) as ID, Submission_Num
FROM [Fiduciary] f
WHERE (Effective_Date < '2017-08-01' AND
       (UABP IS NULL OR USABP IN (0)
      ) OR
      (Effective_Date >= '2017-08-01' AND
       UABP > 0
      ) ;

根据您对问题的描述,我不确定UABP是否是数字或字符串。如果是一个字符串,则在常量周围加上单引号。