SQl查询到条件过滤器

时间:2018-01-18 20:29:59

标签: sql

Div   Acct_Nbr  Site_Nbr Grp  Charge_Cd  
224   8001238   1         1     DSP  
224   8001238   1         1     REG  
224   8001238   1         1     REN  
761   8001238   1         3     DSP  
761   8001238   1         3     REG  
761   8001238   1         3     REN  
902     97161   1         1     BU1  
902     97161   1         1     EXY  
902     97161   1         1     FR3  
902     97161   1         1     REG  

以上是我的数据集,我在寻找Count for

  1. 费用代码='REG'且费用代码='REN'
  2. 的帐户
  3. 具有费用代码='REG'和费用代码<>'REN'
  4. 的帐户

    如果我在我的where子句中保留了充电代码条件1,我就没有结果 我期待的地方如下

    224 8001238 1   1   REG  
    224 8001238 1   1   REN  
    761 8001238 1   3   REG  
    761 8001238 1   3   REN  
    

    对于我期待的子句中的条件二

    902 97161   1   1   REG  
    

    但是我得到了

    224 8001238 1   1   REG  
    761 8001238 1   3   REG  
    902 97161   1   1   REG    
    

3 个答案:

答案 0 :(得分:2)

您必须使用条件聚合。

案例1:

  SELECT Acct_Nbr  
  FROM YourTable
  GROUP BY Acct_Nbr  
  HAVING COUNT(CASE WHEN Charge_Cd = 'REG' THEN 1 END) > 0
     AND COUNT(CASE WHEN Charge_Cd = 'REN' THEN 1 END) > 0

答案 1 :(得分:0)

对于1,我认为问题是记录不能同时为RegRen。这应该是

SELECT * 
FROM {Table} 
WHERE ChargeCd='REG' 
  and Acct_Nbr in
      (SELECT Acct_Nbm FROM {Table} WHERE ChargeCd='REN')

问题类似于你的2:

SELECT * 
FROM {Table} 
WHERE ChargeCd='REG' 
  and Acct_Nbr NOT IN
      (SELECT Acct_Nbm FROM {Table} WHERE ChargeCd='REN')

答案 2 :(得分:0)

SELECT * 
FROM {Table} 
WHERE ChargeCd='REG' 
  and Acct_Nbr in  (SELECT Acct_Nbm 
                    FROM {Table} WHERE ChargeCd='REN')

SELECT * 
FROM {Table} 
WHERE ChargeCd='REG' 
  and Acct_Nbr NOT IN (SELECT Acct_Nbm 
                       FROM {Table} WHERE ChargeCd='REN')

感谢Zebrainatree