2017-01-09 9 views
1

リテラルデータはかなり大量ですが、これを単純化しましたが、非常に単純な例で十分です。大量のデータがあるため、多くの手順ではなく、1回の集計で集計を行うことを検討しています。私はこのクエリで何が間違っているのですか

4 | 4 | 1 

を取得

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 

クエリを実行すると、私はのために...

3 | 4 | 1.3333333... 
探していたとき

は、私は2つのテーブル

<<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 

を持っています

この例は非常に単純化されていますが、実際のケースは非常に大きくなります。私はこれを行う方法があると確信しています、私はちょうど今それが何であるか分かりません。

+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

関連する問題