title: "INVALID USE OF AN AGGREGATE FUNCTION OR OLAP FUNCTION" ERROR IN DB2
body: <p>I have attached my code below for your review.  My error is coming with the 4th CASE statement where I am using math functions to calculate information.  Does anyone know what is causing the error and how to get around it?  I'm guessing that the issue is in my ORDER BY function at the end.</p>
  
  <pre><code>SELECT
  H.DATE AS "DATE"
  ,TRIM(H.NUMBER) AS "NUMBER"
  ,CASE WHEN TT.RY_DATE IS NULL THEN '' ELSE CHAR(TT.RY_DATE) END AS "RY DATE"
  ,CASE WHEN T.PT_DATE = '0001-01-01' THEN 'N' ELSE 'Y' END AS "PT"
  ,T.ON AS "ON"
  ,CASE WHEN H.CLASS = '0.00' THEN H.CLASS ELSE H.RATED END AS "CLASS"
  ,SUBSTR(TRIM(S.NAME), 1, LENGTH(TRIM(S.NAME))-2) AS "CITY"
  ,H.STATE AS "STATE"
  ,H.ZIPCODE AS "ZIP"
  ,SUBSTR(TRIM(CN.NAME), 1, LENGTH(TRIM(CN.NAME))-2) AS "DCITY"
  ,H.STATE AS "DSTATE"
  ,H.ZIPCODE AS "DZIP"
  ,H.WGT AS "WEIGHT"
  ,CASE 
  WHEN Q.AMOUNT IS NULL THEN (Y.CHGS - Z.AMOUNT)
  WHEN Q.AMOUNT IS NOT NULL THEN (Y.CHGS - (SUM(Q.AMOUNT +  Z.AMOUNT))) ELSE ''
  END AS "LL"
  ,Z.AMOUNT AS "FU"
  ,SUM(Q.AMOUNT) AS "AC"
  ,Y.CHGS AS "CHARGES"
  
  FROM A.COST H
  
  INNER JOIN A.MASTER S
  ON H.CITY = S.CITY
  
  INNER JOIN A.MASTER CN
  ON H.CITY = CN.CITY
  
  INNER JOIN A.SPEC Z
  ON Z.NUMBER = H.NUMBER
  AND Z.DATE = H.DATE
  AND Z.TYPE = 'F'
  
  INNER JOIN A.ALT Y
  ON Y.NUMBER = H.NUMBER
  AND Y.DATE = H.DATE
  
  LEFT OUTER JOIN A.SPEC. Q
  ON Q.NUMBER = H.NUMBER
  AND Q.DATE = H.DATE
  AND Q.TYPE = 'S'
  
  LEFT OUTER JOIN A.T TT
  ON H.NUMBER = TT.NUMBER
  
  LEFT OUTER JOIN A.TIME T
  ON T.NUMBER = H.NUMBER
  
  WHERE H.CTRL = '000000'
  AND (MONTH(CURRENT DATE)-1) = MONTH(H.DATE)
  AND H.DATE &gt; CURRENT DATE - 90 DAYS
  
  GROUP BY
  H.DATE 
  ,TRIM(H.NUMBER)
  ,CASE WHEN TT.D_DATE IS NULL THEN '' ELSE CHAR(TT.D_DATE) END
  ,CASE WHEN T.PT_DATE = '0001-01-01' THEN 'N' ELSE 'Y' END
  ,T.ON
  ,CASE WHEN H.CLASS = '0.00' THEN H.CLASS ELSE H.RATED END
  ,SUBSTR(TRIM(S.NAME), 1, LENGTH(TRIM(S.NAME))-2)
  ,H.STATE
  ,H.ZIPCODE 
  ,SUBSTR(TRIM(CN.NAME), 1, LENGTH(TRIM(CN.NAME))-2)
  ,H.STATE 
  ,H.ZIPCODE 
  ,H.WGT 
  ,CASE WHEN Q.AMOUNT IS NULL THEN (Y.CHGS - Z.AMOUNT)
  WHEN Q.AMOUNT IS NOT NULL THEN (Y.CHGS - (SUM(Q.AMOUNT + Z.AMOUNT))) END
  ,Z.AMOUNT 
  ,Y.CHGS
  
  ORDER BY DATE
  </code></pre>