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

SQL SUM and DISTINCT two columns

I have a table called points and based on distinct values of entires, I want to sum valid entries.

I have this:

valid_entries Codes
1 768
2 1224
2 1224
1 512
1 512

Based on distinct values I would have:

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

valid_entries codes
1 768
2 1224
1 512

I want to get the sum of valid_entries that would be 4.

I have tried this one and I have PostgreSQL 11.5 version and I am new to this. I would really appreciate it if anyone could help with this.

SELECT sum(valid_entries) FROM 
(SELECT count(distinct(codes)) FROM points WHERE  participant_id='123') t

>Solution :

First filter out the duplicate rows with DISTINCT and then aggregate:

SELECT SUM(valid_entries) total
FROM (SELECT DISTINCT valid_entries, Codes FROM points WHERE participant_id='123') t;

See the demo.

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