SQL分组的结果与预期不符

时间:2015-05-27 13:04:12

标签: sql oracle group-by

简介详情:

我在使用客户端12c查询Oracle SQL Developer时遇到问题。我已经研究了关于SO的其他几个问题,并搜索了Google的答案,但最终所有答案都包括PG.CAT条款中没有聚合函数的所有列。

我想要的是为每个类别(FD.YEAR)每年,每周和每天(FD.WEEKFD.DTGE.QTY分别获得一个结果) 。我想总结单位,小时数,错误(`SELECT FD.YEAR, FD.WEEK, PG.DT, PG.CAT, SUM(PG.UNITS) AS UNITS, SUM(PG.HOURS) AS HOURS, PM.MTM, PM.MTM * PG.HOURS AS ADJ_MTM, (PG.UNITS / (PM.MTM * PG.HOURS)) AS PERC_STANDARD, SUM(CASE WHEN GE.QTY IS NULL THEN 0 ELSE GE.QTY END) AS QTY, SUM(WH.TOTALHOURS) AS TOTALHOURS FROM PROD_GUNS PG INNER JOIN PROD_MTM PM ON PG.CAT = PM.CATEGORY AND PM.DEPTNO = '018' AND PG.DT BETWEEN PM.START_DT AND PM.END_DT INNER JOIN FISCAL_DATES_DAYS FD ON PG.DT = FD.DT LEFT OUTER JOIN PROD_GUNS_ERRORS GE ON PG.EID = GE.EID AND PG.DT = GE.DT INNER JOIN WEEKLY_HOURS WH ON FD.WEEK = WH.DT_WEEK AND FD.YEAR = WH.DT_YEAR AND PG.EID = WH.EEXX31 GROUP BY FD.YEAR, FD.WEEK, PG.DT, PG.CAT, PM.MTM, PM.MTM * PG.HOURS, (PG.UNITS / ( PM.MTM * PG.HOURS)) HAVING FD.YEAR = '2015' AND FD.WEEK = '1' AND PG.DT = '29-DEC-14' AND PG.CAT = 'Picking' ORDER BY PG.DT;` )和总小时数。我还在两列上执行乘法和除法,并最多连接四个其他表。

查询:

2015    1   29-DEC-14   Picking 46  0.5  68 34      1.35294117647058823529411764705882352941    0   32.21
2015    1   29-DEC-14   Picking 831 7.72 68 524.96  1.58297775068576653459311185614142029869    0   29.35

实际结果:

2015    1   20-Dec-14   Picking 877 8.22 68 558.96   1.21654501216545     0     61.59

预期结果:

{{1}}

问题:

使用上面的聚合和分组,为什么这不会给我预期的结果?提前感谢您提供任何指导。

1 个答案:

答案 0 :(得分:2)

尝试SUM / AVG(取决于你需要的)PM.MTM * PG.HOURS AS ADJ_MTM和(PG.UNITS /(PM.MTM * PG.HOURS))AS PERC_STANDARD,而不是他们分组:

SELECT 
  FD.YEAR, 
  FD.WEEK, 
  PG.DT, 
  PG.CAT, 
  SUM(PG.UNITS) AS UNITS, 
  SUM(PG.HOURS) AS HOURS, 
  PM.MTM,
  SUM(PM.MTM * PG.HOURS )AS ADJ_MTM,
  SUM((PG.UNITS / (PM.MTM * PG.HOURS))) AS PERC_STANDARD,
  SUM(CASE WHEN GE.QTY IS NULL THEN 0 ELSE GE.QTY END) AS QTY,
  SUM(WH.TOTALHOURS) AS TOTALHOURS 
FROM 
  PROD_GUNS PG 
INNER JOIN PROD_MTM PM 
  ON PG.CAT = PM.CATEGORY 
  AND PM.DEPTNO = '018' 
  AND PG.DT BETWEEN PM.START_DT AND PM.END_DT 
INNER JOIN FISCAL_DATES_DAYS FD 
  ON PG.DT = FD.DT 
LEFT OUTER JOIN PROD_GUNS_ERRORS GE 
  ON PG.EID = GE.EID 
  AND PG.DT = GE.DT 
INNER JOIN WEEKLY_HOURS WH
  ON FD.WEEK = WH.DT_WEEK
  AND FD.YEAR = WH.DT_YEAR
  AND PG.EID = WH.EEXX31
GROUP BY 
  FD.YEAR, 
  FD.WEEK, 
  PG.DT, 
  PG.CAT, 
  PM.MTM 
HAVING 
  FD.YEAR = '2015' 
  AND FD.WEEK = '1' 
  AND PG.DT = '29-DEC-14' 
  AND PG.CAT = 'Picking'
ORDER BY 
  PG.DT;