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

Include a column which sums up rows based on criteria

I have some code…

SELECT cEnrol, name, course, month, year, status, fee FROM table

which produces a table like this…

    | cEnrol | name | course | month | year |  status  | fee |
    |--------|------|--------|-------|------|----------|-----|
    |   1    | Aaaa | Zzzzzz |   01  | 2023 |  Active  | 100 |
    |   1    | Aaaa | Zzzzzz |   02  | 2023 |  Active  | 100 |
    |   1    | Aaaa | Zzzzzz |   03  | 2023 | Complete | 100 |
    |   2    | Bbbb | Yyyyyy |   01  | 2023 |  Active  | 200 |
    |   2    | Bbbb | Yyyyyy |   02  | 2023 |  Active  | 200 |
    |   2    | Bbbb | Yyyyyy |   03  | 2023 |  Active  | 200 |
    |   2    | Bbbb | Yyyyyy |   03  | 2023 | Complete | 200 |
    |   3    | Bbbb | Zzzzzz |   03  | 2023 |  Active  | 100 |
    |   3    | Bbbb | Zzzzzz |   03  | 2023 | Complete | 100 |

I would like to include a column that give the total of all fees for all rows with that cEnrol so that I get a table which looks like this…

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

    | cEnrol | name | course | month | year |  status  | fee | sumFees |
    |--------|------|--------|-------|------|----------|-----|---------|
    |   1    | Aaaa | Zzzzzz |   01  | 2023 |  Active  | 100 |   300   | 
    |   1    | Aaaa | Zzzzzz |   02  | 2023 |  Active  | 100 |   300   |
    |   1    | Aaaa | Zzzzzz |   03  | 2023 | Complete | 100 |   300   |
    |   2    | Bbbb | Yyyyyy |   01  | 2023 |  Active  | 200 |   800   |
    |   2    | Bbbb | Yyyyyy |   02  | 2023 |  Active  | 200 |   800   |
    |   2    | Bbbb | Yyyyyy |   03  | 2023 |  Active  | 200 |   800   |
    |   2    | Bbbb | Yyyyyy |   03  | 2023 | Complete | 200 |   800   |
    |   3    | Bbbb | Zzzzzz |   03  | 2023 |  Active  | 100 |   200   |
    |   3    | Bbbb | Zzzzzz |   03  | 2023 | Complete | 100 |   200   |

I have played around with nesting a SELECT statement but run into problems linking the sum back to each cEnrol.

Any ideas?

>Solution :

You can call the sum aggregator and partition by cEnrol.

Something like this :

SELECT
    cEnrol,
    name,
    course,
    month,
    year,
    status,
    fee,
    SUM(fee) OVER (PARTITION BY cEnrol) AS sumFees
FROM
    your_table_name;

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