如何计算子表中的ID?

时间:2016-09-25 14:54:10

标签: sql tsql

我想在两个详细信息表(StandardIDStandardCourses)中计算StandardPosts
我写了这段代码

Select es.StandardID, count(esc.StandardCourseID) as CourseIDCount,
       count(esp.StandardPostID) as PostIDCount
 from EduStandards as es 
      left join EduStandardCourses as esc on es.StandardID = esc.StandardID
      left join EduStandardPosts as esp on es.StandardID = esp.StandardID
 group by es.StandardID

但它返回错误结果:

StandardID | CourseID | PostID
-----------+----------+--------
     3     |     2    |    2
     4     |     1    |    1 
     5     |     1    |    0
     9     |     1    |    0

虽然必须返回:

StandardID | CourseID | PostID
-----------+----------+--------
     3     |     1    |    2
     4     |     1    |    1
     5     |     1    |    0
     9     |     1    |    0

3 个答案:

答案 0 :(得分:0)

Distinct添加到count

Select es.StandardID, count(Distinct esc.StandardCourseID) as CourseIDCount,
       count(esp.StandardPostID) as PostIDCount
 from EduStandards as es 
      left join EduStandardCourses as esc on es.StandardID = esc.StandardID
      left join EduStandardPosts as esp on es.StandardID = esp.StandardID
 group by es.StandardID

一个猜测是StandardCourseID可以有多个StandardPostID。如果有这三个表的样本数据,我们可以写出更合适的答案

Count子表首先

SELECT es.standardid, 
       esp.CourseIDCount, 
       Count(esp.standardpostid)            AS PostIDCount 
FROM   edustandards AS es 
       LEFT JOIN (SELECT Count(StandardCourseID) AS CourseIDCount, 
                         standardid 
                  FROM   edustandardcourses 
                  GROUP  BY standardid) AS esc 
              ON es.standardid = esc.standardid 
       LEFT JOIN edustandardposts AS esp 
              ON es.standardid = esp.standardid 
GROUP  BY es.standardid 

答案 1 :(得分:0)

您可能需要先获取计数才能删除左侧连接中的重复项。

SELECT es.standardid, 
esc.CourseIDCount, 
esp.PostIDCount
FROM   edustandards AS es 
LEFT JOIN
(
    SELECT standardid, Count(StandardCourseID) AS CourseIDCount, 
    FROM   edustandardcourses
    GROUP  BY standardid
) AS esc 
ON es.standardid = esc.standardid

LEFT JOIN
(
    SELECT standardid, Count(StandardPostID) AS PostIDCount, 
    FROM   edustandardposts
    GROUP  BY standardid
) AS esp 
ON es.standardid = esp.standardid

答案 2 :(得分:0)

您可以尝试这样的查询

;WITH CTE_edustandardcourses AS 
(
    SELECT standardid, Count(StandardCourseID) AS StandardCourseCount, 
    FROM   edustandardcourses
    GROUP  BY standardid
), CTE_edustandardposts AS
(
    SELECT standardid, Count(StandardPostID) AS StandardPostCount, 
    FROM   edustandardposts
    GROUP  BY standardid
)
SELECT es.standardid, 
SC.StandardCourseCount AS CourseID, 
SP.StandardPostCount   AS PostID
FROM   edustandards AS es 
LEFT JOIN CTE_edustandardcourses SC
ON es.standardid = SC.standardid
LEFT JOIN CTE_edustandardposts SP 
ON es.standardid = SP.standardid