SQL Server:在同一个where子句中合并两个不同的条件

时间:2017-10-26 08:28:43

标签: sql-server

我有这个问题:

SELECT 
    TRS.UMP AS CR_CODE_DVS, 
    TRSLIG.IdPai AS CR_IDPAI, 
    SUM (CASE WHEN TRS.IdGrp = '06' THEN TRSLIG.MtUMP ELSE 0 END) AS CR_THEO, 
    SUM (CASE WHEN TRS.IdGrp = '07' THEN TRSLIG.MtUMP ELSE 0 END) AS CR_REEL, 
    SUM (CASE WHEN TRS.IdGrp = '08' THEN TRSLIG.MtUMP ELSE 0 END) AS CR_ECART, 
    SUM (CASE WHEN TRS.IdGrp = '04' THEN TRSLIG.MtUMP ELSE 0 END) AS ALIAS_CR_DEPOT, 
    ABS (SUM(CASE WHEN TRS.IdGrp = '05' THEN TRSLIG.MtUMP ELSE 0 END)) AS ALIAS_CR_RETRAIT, 
    SUM (CASE WHEN TRS.IdGrp = '01' AND TRSLIG.Nature = '00' THEN 1 ELSE 0 END) AS CR_NB_TRANSAC
FROM 
    TRSLIG 
INNER JOIN 
    TRS ON TRS.IdTrs = TRSLIG.IdTrs 
WHERE 
    TRS.DateRef = '25-10-2017' 
    AND TRSLIG.Nature = '00' 
    AND TRS.IdGrp IN ('06', '07', '01', '08', '04', '05') 
    AND TRS.IdTpv IS NOT NULL 
GROUP BY 
    TRS.UMP, TRSLIG.IdPai 
HAVING  
    SUM(CASE WHEN TRS.IdGrp = '06' THEN TRSLIG.MtUMP ELSE 0 END) <> 0  
    OR SUM(CASE WHEN TRS.IdGrp = '07' THEN TRSLIG.MtUMP ELSE 0 END) <> 0  
    OR SUM(CASE WHEN TRS.IdGrp = '08' THEN TRSLIG.MtUMP ELSE 0 END) <> 0  
    OR SUM(CASE WHEN TRS.IdGrp = '04' THEN TRSLIG.MtUMP ELSE 0 END) <> 0 
    OR SUM(CASE WHEN TRS.IdGrp = '05' AD TRSLIG.MtUMP <> 0 THEN TRSLIG.MtUMP ELSE 0 END) <> 0

问题是我想添加一个条件来验证当我TRS.IdGrp = '07' or TRS.IdGrp = '08'对应的TRSLIG.MtUMP必须NOT NULL被删除时,我的where子句中有条件承认所有的IdGrps,所以我不知道如何限制这两个IdGrps来使我的状况。

1 个答案:

答案 0 :(得分:0)

你可以试试这个。

SELECT 
   TRS.UMP AS CR_CODE_DVS, TRSLIG.IdPai AS CR_IDPAI, 
   SUM ( CASE WHEN TRS.IdGrp = '06' THEN TRSLIG.MtUMP ELSE 0 END) AS CR_THEO, 
   SUM ( CASE WHEN TRS.IdGrp = '07' THEN TRSLIG.MtUMP ELSE 0 END) AS CR_REEL, 
   SUM ( CASE WHEN TRS.IdGrp = '08' THEN TRSLIG.MtUMP ELSE 0 END) AS CR_ECART, 
   SUM ( CASE WHEN TRS.IdGrp = '04' THEN TRSLIG.MtUMP ELSE 0 END) AS ALIAS_CR_DEPOT, 
   Abs(SUM( CASE WHEN TRS.IdGrp= '05' THEN TRSLIG.MtUMP ELSE 0 END)) AS ALIAS_CR_RETRAIT, 
   SUM ( CASE WHEN TRS.IdGrp ='01' AND TRSLIG.Nature ='00' THEN 1 ELSE 0 END) AS CR_NB_TRANSAC
FROM TRSLIG INNER JOIN TRS 
  ON TRS.IdTrs = TRSLIG.IdTrs 
WHERE 
   TRS.DateRef = '25-10-2017' 
   AND TRSLIG.Nature = '00' 
   AND TRS.IdGrp IN ('06', '07', '01', '08', '04', '05') 
   AND TRS.IdTpv IS NOT NULL 
GROUP BY TRS.UMP, TRSLIG.IdPai 
HAVING  (
       SUM ( CASE WHEN TRS.IdGrp = '06' THEN TRSLIG.MtUMP ELSE 0 END) <> 0  
    or SUM ( CASE WHEN TRS.IdGrp = '07' THEN TRSLIG.MtUMP ELSE 0 END) <> 0  
    or SUM ( CASE WHEN TRS.IdGrp = '08' THEN TRSLIG.MtUMP ELSE 0 END) <> 0  
    or SUM ( CASE WHEN TRS.IdGrp = '04' THEN TRSLIG.MtUMP ELSE 0 END) <> 0 
    or SUM ( CASE WHEN TRS.IdGrp = '05' and TRSLIG.MtUMP<>0 THEN TRSLIG.MtUMP ELSE 0 END ) <> 0
        )
    AND 
     (
        SUM ( CASE WHEN TRS.IdGrp = '07' THEN TRSLIG.MtUMP ELSE 0 END ) IS NOT NULL 
        AND 
        SUM ( CASE WHEN TRS.IdGrp = '08' THEN TRSLIG.MtUMP ELSE 0 END ) IS NOT NULL
     (