sql - Sql 中的除法返回 0 或 NULL
问题描述
SQL 新手并试图解决这个问题。我期待一个获胜百分比的比率,但我得到一个 0 或空列
With previous as (select Venue, Row,
Count(case when place = 1 then 1 else null end) as firstx
Count(case when place = 2 then 1 else null end) as secondx
Count(case when place = 3 then 1 else null end) as thirdx
Count(case when place Between 1 and 15 then 1 else null end) as allplaces
From horses
Where racetitle not like ‘%stand%’
Group by venue, row)
Select case
When firstx = 0
Then Null
Else round(firstx/allplaces, 2)
End as winratio
From previous
Where allplaces > 10;
我想用 secondx 和 thirdx 做到这一点,但不知道为什么它返回一个列为 0 或 Null ???
解决方案
您得到的NULL
原因是firstx = 0
并且0
因为您使用的 rdbms 在除法时进行整数除法,所以在除法之前firstx/allplaces
乘以:1.0
With previous as (
select Venue, Row,
Count(case when place = 1 then 1 end) as firstx
Count(case when place = 2 then 1 end) as secondx
Count(case when place = 3 then 1 end) as thirdx
Count(case when place Between 1 and 15 then 1 end) as allplaces
From horses
Where racetitle not like ‘%stand%’
Group by venue, row
)
Select case
When firstx = 0 Then Null
Else round(1.0 * firstx/allplaces, 2)
End as winratio
From previous
Where allplaces > 10;
我还简化了CASE
里面的表达式,COUNT()
因为没有必要,else NULL
因为这是默认行为。
推荐阅读
- macos - 运行简单的 Selenium Runner 测试时出现“NoSuchSessionError:此驱动程序实例没有有效的会话 ID”
- flask - Falsk "ssl_context" 指向 Google 颁发的 SSL 证书
- node.js - 在导航栏中显示用户名
- ios - 快速转换在类签名中具有泛型的具体类型
- node.js - 如何使用 id 更新 mongoDB 数据?
- javascript - 在引导程序 Vue 表中对行进行分组
- python-3.x - 从大型 request_body 中分块读取数据
- r - 从数据框中创建一个带有嵌套节点的 XML 文件
- ef-fluent-api - 具有 Nullable 引用类型的 .Net Core Fluent API
- docker - 配置 Docker 容器以通过网络进行通信