2017-01-09 40 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