Try modifying the query like shown below:Select distinct p.idpatient ,MAX(Case When c.idtl = 1159 Then c.idtl End ) ,MAX(Case When c.idtl = 1683 Then c.idtl End ) ,MAX(Case When c.idtl = 2423 Then c.idtl End ) ,MAX(Case When c.idtl = 1714 Then c.idtl End ) ,MAX(Case When c.idtl in (2848,1832,1828,1780,1763,1762,1761,1760,1747,1744,1730) Then c.idtl End ) FROM patd pjoin close_results con p.idpatient=c.idpatientGROUP BY p.idpatient
I did not quite follow the logic you are trying to implement, but if you are just interested in patients who have done at least 5 different tests, then the following would do:SELECT idpatientFROM close_results GROUP BY idpatientHAVING COUNT(DISTINCT idtl) >= 5
If you need the details of the tests etc., you can then join this result to the close_results table.