0

以下是我要运行的查询。

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

添加 with between 开始返回空结果。当我将它与硬编码值进行比较时,它返回结果(同样,没有 between)。为了使其通用化,我不能使用硬编码值,即使我给它硬编码值,它也不能在两者之间工作。

更新:Having 不适用于 between,因为它已经选择了一个结果集,其最大值小于 COUNT() 的结果。然而,总是至少有一个范围的最大值大于 COUNT() 的结果。

4

1 回答 1

0

我做错的不是按 ta.minbenchmark 和 ta.maxbenchmark 对结果集进行分组。因此,它只会获得它在技术上发现的第一个 min-max 对的结果,这使得 having 子句无效。所以正确的查询如下(对于任何犯同样错误的人):

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

;

于 2013-09-18T08:03:25.263 回答