sql - 将SQL中两列的计数相除
问题描述
我正在尝试将具有第二列的两列计算为不同的值。第二列数据在第一列中可以有多个值。所以我想计算第一列和第二列的不同计数,并将第一列除以第二列以获得 o/p。现在有第三列我们需要对数据进行分组。
例子:
A B C
----------------
30 10 tomatoes
30 10 tomatoes
5 10 tomatoes
20 5 Potatoes
20 5 Potatoes
40 5 Potatoes
10 15 Onions
40 15 Onions
20 15 Onions
寻找可能的解决方案。
下面是一个简单的尝试。我不确定这是否正确,或者我应该使用分区依据。任何帮助,将不胜感激。
SELECT
C,
COUNT('A') AS A,
COUNT(DISTINCT 'B') AS B,
((COUNT('A')) / COUNT(DISTINCT 'B')) AS AB
FROM
[Table]
GROUP BY
C
ORDER BY
C
解决方案
在这里做除法要小心。当你有 count / count 你有整数数学。所以像 3/2 这样的结果会是 1,而不是 1.5。我稍微修改了您的示例数据以证明我的意思。我在输出中包含了这两个计算,所以你可以区分。
declare @Something table
(
A int
, B int
, C varchar(20)
)
insert @Something values
(30, 10, 'tomatoes')
, (30, 11, 'tomatoes')
, (5 , 10, 'tomatoes')
, (20, 5 , 'Potatoes')
, (20, 5 , 'Potatoes')
, (40, 5 , 'Potatoes')
, (10, 15, 'Onions')
, (40, 15, 'Onions')
, (20, 15, 'Onions')
select count(A)
, count(distinct B)
, count(A) / (count(distinct B) * 1.0) --multiplied by 1.0 to force division to use a decimal
, count(A) / count(distinct B) --integer math
, C
from @Something s
group by C
推荐阅读
- javascript - 在 yii2 中如何将外部 csv 文件引用到 java 脚本中?
- python - 带有列表并单独打印列表的类
- android-fragments - 嵌套滚动视图内的 RecyclerView 的 onBindViewHolder 被一次为所有项目调用
- kubernetes - 恐慌:kafka:客户端已经没有可用的代理与之交谈(您的集群是否可达?)
- html - 如何在 HTML 中导入 react Antd 表?
- jquery - Jquery jsonp响应错误-未返回回调
- python-3.x - Python - 如何从图像中检测和解码多个 Datamatrix
- amazon-web-services - 服务更新完成时 ECS 收到通知?
- javascript - 是否有可以更改 html 元素的样式属性的最大数量?
- android-studio - 如何从 url 获取图像的位图