SQL具有日期范围的语句 - 分组不一致

时间:2015-06-17 17:29:57

标签: sql db2

我正在努力学习这个剧本。我想把它写在它计算实例总数的地方,然后添加这些实例的总和,但是,当我用“HAVING .... AND CSH.SLS_DT BETWEEN'2015-01-01'运行脚本时, '2015-06-16'“我收到一条错误消息,指出 ”分组不一致“

当我注释掉日期范围时,脚本运行正常,但日期范围对此脚本至关重要。预先感谢您的帮助。脚本如下:

SELECT OS.STR_NBR STORE                           
        , CSH.CSHR_USER_ID LDAP                    
        , COUNT(CSH.USER_ID) AS COUNT              
        , SUM(OS.OVR_SHRT_AMT) AS TOTAL            

 FROM PRHDW.VLT_CSHR_AUD CSH                       

 LEFT OUTER 
 JOIN PRHDW.VLT_AUD_OVR_SHRT OS                    
      ON     OS.STR_NBR = CSH.STR_NBR              
      AND    OS.SLS_DT = CSH.SLS_DT                
      AND    OS.CSHR_SYSUSR_ID = CSH.CSHR_SYSUSR_ID

 GROUP BY    OS.STR_NBR, CSH.CSHR_USER_ID          

 HAVING             OS.STR_NBR       = '0121'             
          --AND     SUM (OS.OVR_SHRT_AMT) > 0         
            AND     CSH.SLS_DT BETWEEN '2015-01-01' AND '2015-06-16'  
  ORDER BY TOTAL DESC                                             
  WITH UR;                                                        

1 个答案:

答案 0 :(得分:2)

根据你的约束,它应该与where子句一起使用。 having子句的意图是与某些聚合进行比较。显然你不是这样做的 应改为:

AND    OS.CSHR_SYSUSR_ID = CSH.CSHR_SYSUSR_ID 
WHERE OS.STR_NBR = '0121' 
AND     CSH.SLS_DT BETWEEN '2015-01-01' AND '2015-06-16'
GROUP BY OS.STR_NBR, CSH.CSHR_USER_ID