【问题标题】:SQL - How to display only certain values of the Count Aggregate Function?SQL - 如何仅显示计数聚合函数的某些值?
【发布时间】:2016-09-18 07:09:59
【问题描述】:

我要做的是只显示计数值大于 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 的那些行以上。有没有可行的方法来做到这一点?

【问题讨论】:

  • 只需使用任何有价值的 SQL 教程都包含的 HAVING 子句。

标签: sql oracle select count


【解决方案1】:

使用有:

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

【讨论】:

  • 不客气。请通过单击我的答案上的勾来接受它作为答案
【解决方案2】:

首先不要使用WHERE join 提倡使用显式JOIN sintaxis,Aaron Bertrand 写了一篇很好的文章Bad habits to kick : using old-style JOINs 关于它。

然后使用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; 

另外,如果有人更改 db 上字段的顺序,您的查询不会注意到并且会显示错误行为,我也不会使用 COUNT(1)。使用Count(fieldname)

【讨论】:

  • COUNT(1) 计算包含NULL 值的行数(并且是identical to COUNT(*))- 计数在数字文字1​​(始终是可数的)上,而不是1 表示第一列的值。因此,无论列的顺序如何,结果都将始终相同。
  • 另外COUNT(fieldname) 不会计算fieldname 列的值为NULL 的行,因此它不会总是给出与COUNT(1) 相同的结果。
  • 不,我不是这个意思。 COUNT(1)COUNT(*) 将计算行数(无论任何值是否为 NULL),但 COUNT(column_name) 将仅计算该列中非 NULL 值的数量。跨度>
猜你喜欢
  • 2016-02-01
  • 1970-01-01
  • 2013-08-08
  • 2010-09-17
  • 1970-01-01
  • 1970-01-01
  • 2017-01-29
  • 2015-10-29
  • 1970-01-01
相关资源
最近更新 更多