sql - 如何计算 SQL 组中两个值的比率?
解决方案
例子
Select *
,Ratio = convert(decimal(10,2),
sum(case when [Payment_Mode]='Cash' then [Quantity]+0.0 end) over (Partition By [Item])
/sum(case when [Payment_Mode]='Coupons' then [Quantity] end) over (Partition By [Item])
)
From YourTable
退货
Item Payment_Mode Quantity Ratio
Apples Cash 20 2.00
Apples Coupons 10 2.00
Grapes Cash 45 15.00
Grapes Coupons 3 15.00
Oranges Cash 300 20.00
Oranges Coupons 15 20.00
编辑 - 另一个选项是简单的加入和条件聚合
Select A.*
,B.Ratio
From YourTable A
Join (
Select Item
,Ratio = sum(case when [Payment_Mode]='Cash' then [Quantity]+0.0 end) /NullIF(sum(case when [Payment_Mode]='Coupons' then [Quantity] end),0)
From YourTable
Group By Item
) B on A.Item=B.Item
推荐阅读
- java - @Value 使用 Spring 注入地图地图?
- python - Python Rest客户端api上传文件
- apache-nifi - NiFi - SelectHiveQL 可以以镶木地板格式从 CDH 集群上的表中读取数据吗?
- python - 当我运行我的for循环时,不断收到“AttributeError:'numpy.float64'对象没有属性'append'”
- c++ - 为什么可以修改数组 b?
- mysql - WHERE 条件以某种方式避免全表扫描
- python - 从(元组的元组)中删除重复项
- html - 如何使用 axios 向 img html 标签发出视频流 http GET 请求?
- java - 在哪里可以找到最新的 OpenJDK 8 GA 构建 Windows 10?
- matlab - 读取大量 .h5 数据集