SQL-如何仅显示Count Aggregate函数的某些值?
我试图做的是只显示计数值大于3的行SQL-如何仅显示Count Aggregate函数的某些值?,sql,oracle,select,count,Sql,Oracle,Select,Count,我试图做的是只显示计数值大于3的行 select pharm_name, count(1) as "Number of Staff" from pharmacies p, pharmacy_staff_store pss where p.pharm_id = pss.pharmacy_id group by pharm_name; 例如,此查询可能会返回5行,其中在“人员数量”下会显示例如5,4,3,2,1,但我只希望它返回计数为3及以上的行。有可行的方法吗?使用以下方法: select ph
select pharm_name, count(1) as "Number of Staff"
from pharmacies p, pharmacy_staff_store pss
where p.pharm_id = pss.pharmacy_id
group by pharm_name;
例如,此查询可能会返回5行,其中在“人员数量”下会显示例如5,4,3,2,1,但我只希望它返回计数为3及以上的行。有可行的方法吗?使用以下方法:
select pharm_name, count(1) as "Number of Staff"
from pharmacies p, pharmacy_staff_store pss
where p.pharm_id = pss.pharmacy_id
group by pharm_name
having count(1) > 3
或者你可以这样写:
select * from (
select pharm_name, count(1) as x
from pharmacies p, pharmacy_staff_store pss
where p.pharm_id = pss.pharmacy_id
group by pharm_name)
where x>3
首先不要在加入的地方使用
推广explictJOIN
sintaxis的使用,Aaron Bertrand为此写了一篇很好的文章
然后使用HAVING
从结果中筛选
SELECT pharm_name,
Count(1) AS "Number of Staff"
FROM pharmacies p
JOIN pharmacy_staff_store pss
ON p.pharm_id = pss.pharmacy_id
GROUP BY pharm_name
HAVING COUNT(1) > 3;
另外,如果有人更改数据库中字段的顺序,我不会使用
COUNT(1)
,您的查询不会注意到,并且会显示错误的行为。使用Count(fieldname)
不客气。请通过单击我的答案上的勾号接受它作为答案COUNT(1)
统计行数,包括NULL
值(和is)-计数在数字文字1上(总是可计数的),而不是表示第一列值的1
。因此,无论列的顺序如何,结果总是相同的。COUNT(fieldname)
也不会对fieldname
列的值为NULL
的行进行计数,因此它不会总是给出与COUNT(1)
相同的结果。不,这不是我要说的COUNT(1)
或COUNT(*)
将计算行数(无论任何值是否为NULL
但COUNT(列名称)
将仅计算该列中非NULL
值的数量。只需使用HAVING
子句,任何值得学习的SQL教程都会包含该子句。