Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get average per partition and keep all results

I have a table like this:

company date_num profit
A        EPOCH   12
B        EPOCH   17
A        EPOCH   7
C        EPOCH   9

I would like to calculate average per company and keep the profit column:

company date_num profit  AVG
A        EPOCH   12      9.5
A        EPOCH   7       9.5
B        EPOCH   17      17
C        EPOCH   9       9

So the average column will have the same number(avg) for all rows of a company, and will calculate a single average for all company values.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried:

SELECT company,
AVG(profit) as avg
FROM history
WHERE date_num >= 1617235200 AND date_num <= 1619913600 AND company IN('A','B')
GROUP BY company

Which produce a single line result.

>Solution :

Use AVG as an analytic function:

SELECT company, AVG(profit) OVER (PARTITION BY company) AS avg
FROM history
WHERE date_num >= 1617235200 AND date_num <= 1619913600 AND company IN ('A', 'B');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading