0

How can I Select Distinct values with multiple columns and tables in SQL server?

Here is my code:

SELECT registryno,registrystatus,psPatRegisters.pattrantype,PK_psPatRegisters,
       payername,*
FROM psPatRegisters,psPatinv
WHERE psPatRegisters.PK_psPatRegisters=psPatinv.FK_psPatRegisters
    AND registryno between '7133' and '7169'
    AND psPatinv.pattrantype='I'
GROUP BY psPatRegisters.PK_psPatRegisters

What's wrong with my code?

2
  • 1
    Why you need to use * ? It will select all the columns. Commented Sep 30, 2013 at 5:58
  • Perhaps you could give us a sample of the output you are expecting Commented Sep 30, 2013 at 6:00

3 Answers 3

2

remove the "group by" and "*" and use distinct. Or you have to group by all the selected fields (without *) at that time distinct is not required

Sign up to request clarification or add additional context in comments.

Comments

0

Would that work for you?

select distinct egistryno,registrystatus,
       psPatRegisters.pattrantype,PK_psPatRegisters,payername
from psPatRegisters,psPatinv
where psPatRegisters.PK_psPatRegisters=psPatinv.FK_psPatRegisters
and registryno between '7133' and '7169'
and psPatinv.pattrantype='I'

Also, you cannot group and select columns that are not in the grouping clause without aggregate functions.

Comments

0

All Columns in Projection most be in Group By .

SELECT  registryno ,
    registrystatus ,
    psPatRegisters.pattrantype ,
    PK_psPatRegisters ,
    payername
FROM    psPatRegisters ,
    psPatinv
WHERE   psPatRegisters.PK_psPatRegisters = psPatinv.FK_psPatRegisters
    AND registryno BETWEEN '7133' AND '7169'
    AND psPatinv.pattrantype = 'I'
GROUP BY registryno ,
    registrystatus ,
    psPatRegisters.pattrantype ,
    PK_psPatRegisters ,
    payername

Or Use DISTINCT KeyWord

SELECT  
DISTINCT
    registryno ,
    registrystatus ,
    psPatRegisters.pattrantype ,
    PK_psPatRegisters ,
    payername
FROM    psPatRegisters ,
    psPatinv
WHERE   psPatRegisters.PK_psPatRegisters = psPatinv.FK_psPatRegisters
    AND registryno BETWEEN '7133' AND '7169'
    AND psPatinv.pattrantype = 'I'

and i think if you want only delete duplicate value from your result , best way is use DISTINCT but if you want use aggregate function (Like Sum/Min/...) you most use Group By

Comments

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.