如何查询该列的任何行中都不存在特定数字的列

How do I query a column where a specific number does not exist in any of the rows of that column

我有 ID | Name | Salary 类型分别为 Integer | String | Integer

我需要查询 Salary 列所有行的 avg,然后再次查询 Salary 列所有行的 avg,但是如果其中任何行包含 0,请从这些数字中删除 0,并计算平均值。

所以就像 if Salary returns 1420, 2006, 500,下一个查询应该 return 142, 26, 5。然后我计算后面不包含0的数字的平均值。

我尝试用谷歌搜索我的具体问题,但没有找到任何接近解决方案的方法。我不是在寻找答案,而是在正确的方向上推动。

我的想法

有什么想法吗?希望我很清楚。谢谢!

样本table数据:

ID | Name     | Salary
---+----------+-------
1  | Kathleen | 1420
2  | Bobby    |  690
3  | Cat      |  500

现在我需要查询上面的 table 但是从工资行中删除 0

ID | Name     | Salary
---+----------+-------
1  | Kathleen | 142
2  | Bobby    |  69
3  | Cat      |   5

您只需要条件聚合吗?

select avg(salary), avg(case when salary <> 0 then salary end)
from t;

还是要除法?

select id, name, floor(salary / 10)
from t;

这会产生您指定的结果,但它与“平均”无关。

您想从数字中删除所有 0,然后取结果的数字平均值。如您所见,这需要混合字符串和数字运算。

不同数据库的实际语法会有所不同。在MySQL、SQL Server 和Oracle 中,您应该能够做到:

select avg(replace(salary, '0', '') + 0) as myavg
from mytable

这涉及两个隐式转换步骤:replace() 强制字符串上下文,+ 0 将结果转回数字。在 SQL 服务器中,您将得到一个整数结果 - 如果您想要一个小数平均值,您可能需要添加一个小数值 - 所以 + 0.0 而不是 + 0.

在 Postgres 中,隐式转换不那么容易发生,您可以使用显式转换:

select avg(replace(salary::text, '0', '')::int) as myavg
from mytable

这个returns一个十进制值。