我想按列显示列值的总和。如何显示?

时间:2018-07-26 08:34:50

标签: sql oracle

  SELECT om.unitgroup unit, SUM (COUNT (od.tagno)) AS driftcount
    FROM oehistory od, oeunitmaster om
   WHERE     od.unitcode = om.unitcode
         AND od.status <> 'N'
         AND timestamp BETWEEN TO_DATE ('25-07-2018', 'dd-MM-yyyy')
                           AND TO_DATE ('26-07-2018', 'dd-MM-yyyy')
GROUP BY om.unitgroup
  HAVING COUNT (od.tagno) > 1
ORDER BY od.status ASC;

╔═════════╦════════════╗
║ unit    ║ DriftCount ║
╠═════════╬════════════╣
║  FR     ║          2 ║
║  FR     ║          4 ║
╚═════════╩════════════╝

我想按单位显示差异计数总和。

如何显示?

预期输出是

╔════════╦═════════════════╗
║  unit  ║ totalDriftCount ║
╠════════╬═════════════════╣
║  FR    ║               6 ║
╚════════╩═════════════════╝

错误是

  

ORA-00937:不是单组分组功能   00937. 00000-“不是单组分组功能”   *原因:
  *动作:

1 个答案:

答案 0 :(得分:0)

如果按某列排序,则需要将其包括在group by子句中。 因此,如果需要此排序,则必须分组:

SELECT om.unitgroup unit, SUM(od.tagno) as DriftSum,  COUNT(od.tagno) AS DriftCount
    FROM oehistory od, oeunitmaster om
   WHERE     od.unitcode = om.unitcode
         AND od.status <> 'N'
         AND timestamp BETWEEN TO_DATE('25-07-2018', 'dd-MM-yyyy') AND TO_DATE('26-07-2018', 'dd-MM-yyyy')
GROUP BY om.unitgroup, od.status
  HAVING COUNT(od.tagno) > 1
ORDER BY od.status ASC

对于每个od.status值,这将为您提供与om.unitgroup一样多的行。

不同地,如果您不希望按状态拆分行,则必须删除order by子句:

SELECT om.unitgroup unit, SUM(od.tagno) as DriftSum,  COUNT(od.tagno) AS DriftCount
    FROM oehistory od, oeunitmaster om
   WHERE     od.unitcode = om.unitcode
         AND od.status <> 'N'
         AND timestamp BETWEEN TO_DATE('25-07-2018', 'dd-MM-yyyy') AND TO_DATE('26-07-2018', 'dd-MM-yyyy')
GROUP BY om.unitgroup
  HAVING COUNT(od.tagno) > 1