简体   繁体   中英

SQL - Count with LEFT OUTER JOIN is incorrect

I'm trying to retrieve fields from the issue table along with related record counts from the comment table and the issue_assigneduser table. If there are 2 comments and 6 assigned users, the values I get back are 12 for both counts. Any idea how to remedy this?

SELECT issue.issueid, COUNT(comment.commentid) AS CountOfComments, 
    Count(issue_assigneduser.userid) as CountOfAssignedUsers, 
    issue.title, issue.detail, issue.enteredby, 
    issue.datetimeentered, issue.assignedto, issue.categoryid,  
    issue.severityid, issue.statusid, 
    issue.lastcommentdatetime as LastCommentDateTime, 
    issue.lastcommentbyuserid, 
    users.initials as LastCommentUserInitials,  
    lookupstatus.status as Status, 
    lookupcategory.category as Category, 
    lookupseverity.severity as Severity, 
    GetUTCDate() as UTCDateTime  
FROM issue
    INNER JOIN lookupcategory ON issue.categoryid = lookupcategory.categoryid
    INNER JOIN lookupseverity ON issue.severityid = lookupseverity.severityid
    INNER JOIN lookupstatus ON issue.statusid = lookupstatus.statusid
    LEFT OUTER JOIN  comment ON issue.issueid = comment.issueid
    LEFT OUTER JOIN  issue_assigneduser ON issue.issueid = issue_assigneduser.issueid
    LEFT OUTER JOIN  users ON issue.lastcommentbyuserid = users.userid  
GROUP BY issue.issueid, issue.title, issue.detail, 
    issue.enteredby, issue.datetimeentered, 
    issue.assignedto, issue.categoryid, 
    issue.severityid, issue.statusid,  
    issue.lastcommentdatetime, 
    issue.lastcommentbyuserid, 
    users.initials, lookupstatus.status, 
    lookupcategory.category, 
    lookupseverity.severityid, users.initials, 
    lookupstatus.status, lookupcategory.category, 
    lookupseverity.severity  
ORDER BY issue.lastcommentdatetime DESC;

Use COUNT( DISTINCT fieldname ) instead of COUNT ( fieldname )

Eg for users

Count(DISTINCT issue_assigneduser.userid) as CountOfAssignedUsers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM