tags:

views:

214

answers:

1

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.)

+6  A: 

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
codeulike
Yup, that's it. Thanks. I was so close.
Grant