With tables basically like this:
Elements
id INT PRIMARY KEY
...
Observations
id INT PRIMARY KEY
...
Data
id INT PRIMARY KEY
observation_id FOREIGN KEY
element_id FOREIGN KEY
value FLOAT
...
I want to find all observation_ids where there are duplicate element_ids in a single observation_id. For example, if I have Data records like:
1|50|23|4.5
2|50|24|9.9
3|66|23|4.4
4|66|23|4.1
Then the query would report observation_id 66 because it has two associated rows with element_id 23.
(I'm using PostgreSQL, but this is probably a basic SQL question.)
Use the count() aggregate combined with a 'having' clause:
select observation_id, element_id, count(*) from Data group by observation_id, element_id having count(*) > 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With