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 – different Id with same value then True without subquery

I try to transform following table without a subquery:

Document     Reader 
doc1         John
doc2         Max
doc2         John

This would be my desired result :

Reader      Duplicate
John        True
Max         False

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

>Solution :

Use group by to get the readers distinct, and count in a case to determine they are duplicate

declare @t table (Document varchar(10), Reader varchar(10))
insert into @t values ('doc1', 'John'), ('doc2', 'Max'), ('doc2', 'John')

select t.Reader, 
       case when count(Document) > 1 then 'True' else 'False' end as Duplicate
from   @t t
group by t.Reader

And if you need Duplicate as a bit column, than use this

select t.Reader, 
       convert(bit, case when count(Document) > 1 then 1 else 0 end) as Duplicate
from   @t t
group by t.Reader

You can try it out yourself in DBFiddle

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