简体   繁体   中英

Oracle SQL — Grouping aggregate function with analytic functions?

I have SQL like this:

SELECT
  TO_CHAR(dateinvoiced, 'YYYY') AS year,
  TO_CHAR(dateinvoiced, 'MM') AS month,      
  name,
  SUM(reste) OVER (PARTITION BY name, ad_org_id) AS tot_reste_client,
  nameregion AS region
FROM
  table
GROUP BY
  TO_CHAR(dateinvoiced, 'YYYY'),
  TO_CHAR(dateinvoiced, 'MM'),      
  name,
  nameregion
ORDER BY name;

I get tried to put it in the GROUP BY clause and i get error like this "Is not group function",tried using HAVING and it tell me "window functions are not allowed here".

Couldn't find solution?, i'm using Oracle 12.

Analytic functions are calculated after GROUP BY/HAVING, so usually you can add aggregation to reste :

SELECT
  TO_CHAR(dateinvoiced, 'YYYY') AS year,
  TO_CHAR(dateinvoiced, 'MM') AS month,      
  name,
  SUM(SUM(reste)) OVER (PARTITION BY name, ad_org_id) AS tot_reste_client,
  nameregion AS region
FROM
  table
GROUP BY
  TO_CHAR(dateinvoiced, 'YYYY'),
  TO_CHAR(dateinvoiced, 'MM'),      
  name,
  nameregion
ORDER BY name;

But this should also fail due to ad_org_id , which is not in GROUP BY, maybe you can use a MIN(ad_org_id) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM