首页 > 解决方案 > 将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

标签: sqlsql-servertsql

解决方案


在这里做除法要小心。当你有 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

推荐阅读