MYSQL-之间返回空结果

时间:2013-09-18 07:32:56

标签: mysql having-clause

以下是我正在尝试运行的查询。

SELECT p_date,TS.substationid,ts.substationcode,ts.manufacturingproductid,ts.assemblylineid,ts.teamid,ts.subofficecode,
TA.AllowID,ta.allowname,ta.minbenchmark,ta.maxbenchmark,COUNT(vfp.UnitsPass) Achieved,
            CASE TA.RewardType 
                    WHEN 'Monthly' THEN 
                          TA.RewardValue/DAY(LAST_DAY(P_Date))
                WHEN 'Yearly' THEN
                          TA.RewardValue/((STR_TO_DATE(CONCAT(EXTRACT(YEAR FROM P_Date),1,1),'%Y%m%d')) /(STR_TO_DATE(CONCAT(EXTRACT(YEAR FROM P_Date),12,31), '%Y%m%d')))
                WHEN 'Daily' THEN
                          (TA.RewardValue*12)/365           
                 END-- , 0) 
                 AS Allowance
FROM tempsubstation ts
LEFT JOIN TempAllowances ta ON ts.manufacturingproductid=ta.manufacturingproductid AND ts.subofficecode=ta.subofficecode
LEFT JOIN wms_vfproduction vfp ON DATE(vfp.CreationDate)=p_date AND vfp.StationCode='1600150'
WHERE ta.AllowID=41 AND vfp.UnitsPass=1
 GROUP BY p_date,substationcode
 HAVING COUNT(vfp.UnitsPass) BETWEEN ta.minbenchmark AND ta.maxbenchmark

在开始之间添加返回空结果。当我将其与硬编码值进行比较时,它返回结果(再次,没有之间)。为了保持它的一般化,我不能使用硬编码值,即使我给它硬编码值,也不能用于它们之间。

UPDATE :之间无法使用,因为它已经选择了一个范围,其中max小于COU​​NT()的结果。但是,始终至少有一个范围的最大值大于COUNT()的结果。

1 个答案:

答案 0 :(得分:0)

我错误的是没有对ta.minbenchmark和ta.maxbenchmark的结果集进行分组。因此,它只能得到第一个最小 - 最大对的结果,它在技术上使得条款无效。所以正确的查询如下(对于犯同样错误的人):

SELECT p_date,TS.substationid,ts.substationcode,ts.manufacturingproductid,ts.assemblylineid,ts.teamid,ts.subofficecode,
TA.AllowID,ta.allowname,ta.minbenchmark,ta.maxbenchmark,COUNT(vfp.UnitsPass) Achieved,
            CASE TA.RewardType 
                    WHEN 'Monthly' THEN 
                          TA.RewardValue/DAY(LAST_DAY(P_Date))
                WHEN 'Yearly' THEN
                          TA.RewardValue/((STR_TO_DATE(CONCAT(EXTRACT(YEAR FROM P_Date),1,1),'%Y%m%d')) /(STR_TO_DATE(CONCAT(EXTRACT(YEAR FROM P_Date),12,31), '%Y%m%d')))
                WHEN 'Daily' THEN
                          (TA.RewardValue*12)/365           
                 END-- , 0) 
                 AS Allowance
FROM tempsubstation ts
LEFT JOIN TempAllowances ta ON ts.manufacturingproductid=ta.manufacturingproductid AND ts.subofficecode=ta.subofficecode
LEFT JOIN wms_vfproduction vfp ON DATE(vfp.CreationDate)=p_date AND vfp.StationCode='1600150'
WHERE ta.AllowID=41 AND vfp.UnitsPass=1
 GROUP BY p_date,substationcode,ta.minbenchmark,ta.maxbenchmark
  HAVING COUNT(vfp.UnitsPass) BETWEEN ta.minbenchmark AND ta.maxbenchmark