如何检索SELECT语句

时间:2015-07-02 18:01:24

标签: sql sql-server join totals

我正在尝试检索正确的记录数以减轻我遇到的问题。以下查询从我的数据库中返回327条记录:

 SELECT DISTINCT COUNT(at.someid) AS CountOfStudentsInTable FROM tblJobSkillAssessment AS at 
                INNER JOIN tblJobSkills j ON j.jobskillid = at.skillid
                LEFT JOIN tblStudentPersonal sp ON sp.someid2 = at.someid
                INNER JOIN tblStudentSchool ss ON ss.monsterid = at.someid
                INNER JOIN tblSchools s ON s.schoolid = ss.schoolid
                INNER JOIN tblSchoolDistricts sd ON sd.schoolid = s.schoolid
                INNER JOIN tblDistricts d ON d.districtid = sd.districtid
                INNER JOIN tblCountySchools cs ON cs.schoolid = s.schoolid
                INNER JOIN tblCounties cty ON cty.countyid = cs.countyid
                INNER JOIN tblRegionUserRegionGroups rurg ON rurg.districtid = d.districtid
                INNER JOIN tblGroups g ON g.groupid = rurg.groupid
                WHERE ss.graduationyear IN (SELECT Items FROM FN_Split(@gradyears, ',')) AND sp.optin = 'Yes' AND g.groupname = @groupname

我遇到麻烦的地方是尝试将其与下面的查询进行协调。一个是仅显示所有特定学生的计数,另一个是根据需要显示一组学生的相关信息,但总需要相同而不是。以下查询返回333名学生 - 原因是学生所在的学校位于两个不同的县,并且该学生两次计算。我无法弄清楚如何解决这个问题。

 SELECT DISTINCT @TableName AS TableName, d.district AS LocationName, cty.county AS County, COUNT(DISTINCT cc.monsterid) AS CountOfStudents, d.IRN AS IRN FROM tblJobSkillAssessment AS cc
            INNER JOIN tblJobSkills AS c ON c.jobskillid = cc.skillid
            INNER JOIN tblStudentPersonal sp ON sp.monsterid = cc.monsterid
            INNER JOIN tblStudentSchool ss ON ss.monsterid = cc.monsterid
            INNER JOIN tblSchools s ON s.schoolid = ss.schoolid
            INNER JOIN tblSchoolDistricts sd ON sd.schoolid = s.schoolid
            INNER JOIN tblDistricts d ON d.districtid = sd.districtid
            INNER JOIN tblCountySchools cs ON cs.schoolid = s.schoolid
            INNER JOIN tblCounties cty ON cty.countyid = cs.countyid
            INNER JOIN tblRegionUserRegionGroups rurg ON rurg.districtid = d.districtid
            INNER JOIN tblGroups g ON g.groupid = rurg.groupid
            WHERE ss.graduationyear IN (SELECT Items FROM FN_Split(@gradyears, ',')) AND sp.optin = 'Yes' AND g.groupname = @groupname
            GROUP BY cty.county, d.IRN, d.district
            ORDER BY LocationName ASC

1 个答案:

答案 0 :(得分:1)

如果你只是想要计数,那么count(distinct)可能会解决问题:

select count(distinct at.someid)

我不知道at.someid指的是什么,所以也许:

select count(distinct cc.monsterid)