根据计数显示SQL查询结果

时间:2017-12-15 16:17:24

标签: mysql sql

我正在寻找一种只根据计数显示查询结果的方法。我有以下内容:

# 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;

非常感谢任何帮助。谢谢。

2 个答案:

答案 0 :(得分:0)

WHERE限制您正在使用的记录。此时聚合结果"Needed Updates"不存在。如果要过滤聚合结果,请使用HAVING

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

BTW:MySQL允许HAVING中的列别名。但是,在标准SQL中不允许这样做,您需要GROUP BY count(systems2updates.2package)

更新:在报价方面,MySQL并不总是符合标准。 MySQL可以为字符串采用双引号中的别名。最好避免使用这些别名。

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;

答案 1 :(得分:0)

我假设您只想返回COUNT大于某个值的行?如果是这种情况,HAVING子句是最简单的方法。例如:

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

请注意,HAVING效果不佳,您可能希望使用ROW_NUMBER()函数查看替代解决方案。