Home > other >  SQL SUM and DISTINCT two columns
SQL SUM and DISTINCT two columns

Time:11-06

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:

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

CodePudding user response:

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.

  • Related