2017-01-09 167 views
1

我已經簡化了這一點,因爲文字數據非常龐大,但一個非常簡單的例子就足夠了。我正在研究一個查詢,因爲大量的數據,我正在尋找一些聚合,而不是許多步驟。我在這個查詢中做錯了什麼

我有兩個表

<<customers>> 
id | first_name | last_name 
1 | Reed  | Richards 
2 | Johnny  | Storm 
3 | Peter  | Parker 

<<purchases>> 
id | cid | date 
1 | 1 | 2017-01-09 
2 | 2 | 2017-01-09 
3 | 2 | 2017-01-09 
4 | 3 | 2017-01-09 

當我運行查詢

SELECT 
    COUNT(c.id) as "Total Customers", 
    COUNT(p.id) as "Total Sales", 
    COUNT(c.id)/COUNT(p.id) as "Sales per customer" 
FROM test_customers c 
    LEFT OUTER JOIN test_purchases p ON c.id = p.cid 

我得到

4 | 4 | 1 

當我在尋找......

3 | 4 | 1.3333333... 

這個例子非常簡單,但真正的例子是大得多。我確信有一種方法可以做到這一點,我只是不確定現在是什麼。

+2

查找如何將數據轉換爲小數/浮動。 – dfundako

+1

[獲得確切的結果數字除法](http://stackoverflow.com/questions/16963926/get-exact-result-for-number-division) – Mixone

+0

可能的重複http://stackoverflow.com/questions/16963926/get-exact-result-for-number-division也看看使用:: float – Mixone

回答

1

您正在嘗試不同的計數行,而不是使用count(distinct ...)

SELECT 
    COUNT(distinct c.id) as "Total Customers", 
    COUNT(distinct p.id) as "Total Sales", 
    COUNT(distinct c.id)/COUNT(distinct p.id) as "Sales per customer" 
FROM test_customers c 
    LEFT OUTER JOIN test_purchases p ON c.id = p.cid 

注意,性能是不是很大

+1

你需要將count()轉換爲decimal,否則這個函數不會返回任何小數值 –

+0

@a_horse_with_no_name隨意編輯 – JohnHC

相關問題