如何在SQL Server中使用多个列和表选择不同的值?

时间:2013-09-30 05:54:41

标签: sql-server sql-server-2008

如何在SQL Server中使用多个列和表选择不同的值?

这是我的代码:

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

我的代码出了什么问题?

3 个答案:

答案 0 :(得分:2)

删除“group by”和“*”并使用distinct。或者您必须按所有选定的字段进行分组(不使用*),此时不需要使用

答案 1 :(得分:0)

这会对你有用吗?

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'

此外,如果没有聚合函数,则无法对不在分组子句中的列进行分组和选择。

答案 2 :(得分:0)

投影中的所有列大多数都在分组依据中。

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

或使用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'

我认为如果您只想从结果中删除重复值,最好的方法是使用DISTINCT 但如果你想使用聚合函数(如Sum / Min / ...),你最常使用Group By