简体   繁体   中英

Error in Count(),Group by and Joins in sql server

the result is very different when i separated statements...

SELECT Company.CompanyID,
Count(Projects2.CompanyID) as TotalProjects,
Count(Jobs2.CompanyID) as TotalJobs,
Count(Employees.CompanyID) as TotalEmployess
FROM Company JOIN
Projects2 ON Company.CompanyID = Projects2.CompanyID  
JOIN Company Employees ON Company.CompanyID = Employees.CompanyID 
JOIN Company Jobs2 ON Jobs2.CompanyID = Company.CompanyID
Group by Company.CompanyID

the result

在此输入图像描述

why repeat the values? any ideas?

Your query is joining to the Company table 3 times (aliasing it as Employees and Jobs2 in the later instances). Just a typo?

你在每个列“TotalProjects”,“TotalJobs”和“TotalEmployees”中得到相同的值,因为你的JOIN(将来考虑使用INNER JOIN,因为它做同样的事情,但更清楚)正在生产结果在连接表中存在匹配值 - 因此您将得到每个结果的相同数量。

I think you are counting the wrong ID. What is the primary key for the projects2, jobs2 and employees tables? Your query should be like this:

SELECT Company.CompanyID,
COUNT(DISTINCT Projects2.Primary_Key) as TotalProjects,
COUNT(DISTINCT Jobs2.Primary_Key) as TotalJobs,
COUNT(DISTINCT Employees.Primary_Key) as TotalEmployees
FROM Company
LEFT JOIN Projects2 ON Company.CompanyID = Projects2.CompanyID  
LEFT JOIN Employees ON Company.CompanyID = Employees.CompanyID 
LEFT JOIN Jobs2 ON Company.CompanyID = Jobs2.CompanyID 
GROUP BY Company.CompanyID

Also, use LEFT joins instead of just JOIN and you don't need to keep repeating Company.

The reason you are getting the same count for each table is because of your joins. Say there are five records in the projects table with a given company ID but there are only three records in the jobs table with that ID. When you join company table to the project table you will have five records. Then when you join the jobs table, your joined table will have 15 (5*3) records for that company ID, because each job record will join to each of the five project records. Hence, you only want to select the distinct records from each table, using their primary key.

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