[英]Divide the count of two columns in 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
尋找可能的解決方案。
下面是一個簡單的嘗試。 我不確定這是否正確,或者我應該使用 partition by。 任何幫助,將不勝感激。
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
您的查詢邏輯是正確的,但包含一些錯字:
這將是 :
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('A')
,它將返回表中的行數而不是 A 列的計數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.