某些行的总和

时间:2015-06-30 05:07:17

标签: sql sql-server count sum

我正在尝试计算我得到的结果集的计数,但无法弄清楚如何计算。这是我的SQL语句:

SELECT c.clustername AS Clustername, d.district AS LocationName, cty.county AS County, CAST(COUNT(DISTINCT cc.monsterid) AS VARCHAR(MAX)) AS ClusterCount,    d.IRN AS IRN FROM tblCareerCluster cc 
        INNER JOIN tblClusters c ON c.clusterid = cc.clusterid
        LEFT 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 cc.ranking = @maxrank AND sp.optin = 'Yes' AND c.clustername = @clustername AND g.groupname = @groupname
        GROUP BY s.school, cc.monsterid, c.clustername, cty.county, s.IRN, d.IRN, d.district
        ORDER BY LocationName ASC

以下是我的回复:

Manufacturing Technologies  1   000162  Newark Digital Academy
Manufacturing Technologies  1   048306  Boardman High School
Manufacturing Technologies  1   045278  Carrollton High School
Manufacturing Technologies  1   050237  Chalker High School
Manufacturing Technologies  1   043760  Circleville High School
Manufacturing Technologies  1   043778  Claymont High School
Manufacturing Technologies  1   043778  Claymont High School

正如你所看到的,我希望Claymont高中实际上说2而不是每行显示两次。鉴于上述查询和聚合功能,我该如何做到这一点。我需要上面查询中的行和它们的列,但我需要正确计算结果。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:0)

在没有真正了解你的桌子的情况下,蛮力的方式; - ):

将整个SELECT放入子查询中,然后对其执行SELECT ... GROUP BY

修改

我想帮助您进一步解决您的问题,但MCVE在这里会有所帮助! 此外,您的问题中存在某些不准确之处: 您的select语句应该会产生一个包含5列的输出:

SELECT c.clustername                                      AS Clustername,   // Manufacturing Technologies
       d.district                                         AS LocationName,  // Claymont High School
       cty.county                                         AS County,        // ?
       CAST(COUNT(DISTINCT cc.monsterid) AS VARCHAR(MAX)) AS ClusterCount,  // ?
       d.IRN                                              AS IRN            // ?
FROM tblCareerCluster cc  ...

到目前为止,我只能将您引用的4列中的2列标识为“结果”。您从哪个列获得1043778?!?

答案 1 :(得分:0)

您好我的建议是不使用先前的计数,只需选择使用连接,条件分组子句从一组表中获取数据所需的列。如果它(在某种意义上,选择查询给出的结果没有任何错误)正常工作然后使用select count(*) from (your select query);