0

I have two tables. The screenshots with the following structure:

  1. id (bigint)
  2. originalFilename (string)
  3. createdAt (Date)

And the second is screenshotSignatures:

  1. screenshotId (foreign key for screenshots)
  2. signature (bigint)

So the screenshots table has one to many relation. So now I need to find all duplicates. It means screenshot has exactly the same signatures. I tried to do following:

SELECT os.id, os."originalFilename", array_agg(signature) as signatures from "development".screenshots os
left join development."screenshotSignatures" s on os.id = s."screenshotId"
WHERE GROUP BY os.id, os."originalFilename" ;

and from this query I get the following result: enter image description here

So now I need to find out the duplicates somehow, but I don't know to do it. I thought I can do it some how from screenshotSignatures table. As a result it will be nice to have smth like: screenshots (a,b,c) have the same set of signatures. Later I'll need to delete the oldest screenshots. Any ideas? Thank you

1 Answer 1

1

Simply use the HAVING clause:

WITH signature_list AS (
  SELECT os.id, os."originalFilename", array_agg(signature ORDER BY signature) as signatures 
  from "development".screenshots os
  left join development."screenshotSignatures" s on os.id = s."screenshotId"
  GROUP BY os.id, os."originalFilename"
)
SELECT signatures, array_agg(id) as duplicate_ids, array_agg(originalFilename) as duplicate_filenames
FROM signature_list 
GROUP BY signatures
HAVING COUNT(*) > 1
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for your answer but it says: Unable to resolve column signatures in HAVING clause. Am I did smth wrong?
Okay, let's first aggregate the signatures for each filename - and then find duplicate signatures.
It sounds cool, but how to do it? Could you provide some code?
I updated my answer - it does the aggregation inside the CTE and then uses the HAVING clause.
Thank you man! You're my hero!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.