在SQL Server中使用distinct的正确方法

时间:2014-10-24 00:34:30

标签: sql-server

我正在尝试根据查询检索一些记录

Select distinct 
    tblAssessmentEcosystemCredit.AssessmentEcosystemCreditID,
    tblSpecies.CommonName 
from 
    tblAssessmentEcosystemCredit
left join 
    tblSpeciesVegTypeLink on tblAssessmentEcosystemCredit.VegTypeID = tblSpeciesVegTypeLink.VegTypeID 
left join 
    tblSpecies on tblSpecies.SpeciesID = tblSpeciesVegTypeLink.SpeciesID
where 
    tblAssessmentEcosystemCredit.SpeciesTGValue < 1 

上面的查询返回17,000条记录但是当我删除tblSpecies.CommonName时,它只检索4200条(这实际上是正确的)。

我不知道如何仅区分tblAssessmentEcosystemCredit.AssessmentEcosystemCreditID列并检索查询中的所有其他表列。

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:1)

此查询选择AssessmentEcosystemCreditID和CommonName的不同COMBINATION;如果你想要每个值的AssessmentEcosystemCreditID只有一行,那么你需要使用GROUP BY,如@JonasB所建议的那样;但是,在这种情况下,每个EvaluEcosystemCreditID值可能有几个CommonName值,因此SQL要求您指定所需的WHICH

Select  tblAssessmentEcosystemCredit.AssessmentEcosystemCreditID ,
         max(tblSpecies.CommonName) as CommonName,
         min(tblSpecies.CommonName) as CommonName2, -- so you can verify you only have one value
 from tblAssessmentEcosystemCredit
 left join tblSpeciesVegTypeLink 
      on tblAssessmentEcosystemCredit.VegTypeID = tblSpeciesVegTypeLink.VegTypeID 
 left join tblSpecies on tblSpecies.SpeciesID= tblSpeciesVegTypeLink.SpeciesID
 where tblAssessmentEcosystemCredit.SpeciesTGValue <1
 GROUP BY tblAssessmentEcosystemCredit.AssessmentEcosystemCreditID