简体   繁体   English

如何计算 SQL 中 select 的结果

[英]How do I count the results of a select in SQL

I was given the following question for an assignment我被分配了以下问题

Write a SQL statement to show the sum of Hours Worked for each Type of OWNER but exclude services of employees who have Experience Level of Junior and exclude any Owner Type with Less Than Four members编写 SQL 语句以显示每种所有者类型的工作时间总和,但不包括经验级别为初级的员工的服务,并排除任何少于四名成员的所有者类型

I'm having a hard time figuring out how to accomplish the last part of the question.我很难弄清楚如何完成问题的最后一部分。 I believe that it would require counting a portion of a select statement but I'm not sure how to do that.我相信这需要计算 select 语句的一部分,但我不知道该怎么做。

So far, this is what I have:到目前为止,这就是我所拥有的:

 SELECT SUM(HoursWorked), OwnerType 
 FROM PROPERTY_SERVICE 
 JOIN EMPLOYEE ON EMPLOYEE.EmployeeID=PROPERTY_SERVICE.EmployeeID
 JOIN OWNED_PROPERTY ON OWNED_PROPERTY.PropertyID = PROPERTY_SERVICE.PropertyID
 INNER JOIN OWNER ON OWNER.OwnerID=OWNED_PROPERTY.OwnerID 
 WHERE NOT EMPLOYEE.ExperienceLevel='Junior' 
 *This is where I believe the solution should go*
 GROUP BY OWNER.OwnerType;

Presumably, you just want a HAVING clause:据推测,您只需要一个HAVING子句:

SELECT SUM(HoursWorked), o.OwnerType 
FROM PROPERTY_SERVICE ps
JOIN EMPLOYEE e        ON e.EmployeeID  = ps.EmployeeID
JOIN OWNED_PROPERTY op ON op.PropertyID = ps.PropertyID
INNER JOIN OWNER o     ON o.OwnerID     = op.OwnerID 
WHERE e.ExperienceLevel <> 'Junior' 
GROUP BY o.OwnerType
HAVING COUNT(*) < 4

This excludes groups of rows having the same OwnerType that contain less than 4 rows.这不包括具有相同OwnerType包含少于 4 行的行组。 You might need to adjust the expression to your exact definition of a member .您可能需要将表达式调整为您对member的确切定义。

Note that I added table aliases to the query to make it easier to read and write.请注意,我在查询中添加了表别名以使其更易于阅读和编写。 I would also recommend prefixing column HoursWorked with the table it belongs to, to avoid ambiguity.我还建议在列HoursWorked之前为其所属的表添加前缀,以避免歧义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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