简体   繁体   English

显示基于计数的SQL查询结果

[英]Show SQL query results based on a count

I am looking for a way to only show results of a query based upon a count. 我正在寻找一种仅基于计数显示查询结果的方法。 I have the following: 我有以下几点:

# Returns expected number
SELECT systems.hostname AS Hostname, systems.date AS "Last Checked In", count(systems2updates.2package) AS "Needed Updates" 
FROM systems2updates RIGHT JOIN systems on systems2updates.2hostname=systems.hostname 
GROUP BY systems.hostname;

# Shows all entires, including those with 0
SELECT systems.hostname AS Hostname, systems.date AS "Last Checked In", count(systems2updates.2package) AS "Needed Updates" FROM systems2updates 
RIGHT JOIN systems on systems2updates.2hostname=systems.hostname 
WHERE "Needed Updates" > 0 
GROUP BY systems.hostname;

# Returns nothing
SELECT systems.hostname AS Hostname, systems.date AS "Last Checked In", count(systems2updates.2package) AS "Needed Updates" 
FROM systems2updates RIGHT JOIN systems on systems2updates.2hostname=systems.hostname WHERE "Needed Updates" = 0 
GROUP BY systems.hostname;

Any assistance greatly appreciated. 任何帮助,不胜感激。 Thank you. 谢谢。

WHERE limits the records you are using. WHERE限制您正在使用的记录。 The aggregation result "Needed Updates" does not exist at that moment. 聚合结果"Needed Updates"当时不存在。 If you want to filter on aggregation results, use HAVING : 如果要过滤聚合结果,请使用HAVING

...
GROUP BY systems.hostname
HAVING "Needed Updates" = 0;

BTW: MySQL allows column aliases in HAVING . 顺便说一句:MySQL允许在HAVING使用列别名。 This is not allowed in standard SQL however, where you would have to GROUP BY count(systems2updates.2package) . 但是,这在标准SQL中是不允许的,在这种情况下,您必须使用GROUP BY count(systems2updates.2package)

UPDATE: MySQL is not always standard-compliant when it comes to quotes. 更新:在引用方面,MySQL并不总是符合标准。 Alias names in double quotes can be taken for a string by MySQL. MySQL可以将双引号的别名用作字符串。 Better avoid such alias names. 最好避免使用此类别名。

select 
  s.hostname as hostname, 
  s.date as last_checked_in, 
  count(su.2package) as needed_updates 
from systems s
left join systems2updates su on su.2hostname = s.hostname
group by s.hostname
having count(su.2package) = 0;

I assume you are looking to only return rows where the COUNT is greater than a certain value? 我假设您只想返回COUNT大于特定值的行? If that's the case, the HAVING clause is the easiest way. 如果是这样,那么HAVING子句是最简单的方法。 For example: 例如:

SELECT sampleValue, COUNT(*)
FROM dbo.SomeTable
GROUP BY sampleValue
HAVING COUNT(*) > 5

Note that HAVING does not perform well, and you may want to look at an alternative solution using the ROW_NUMBER() function. 请注意,HAVING的性能不佳,您可能希望使用ROW_NUMBER()函数查看替代解决方案。

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

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