为什么我的查询涉及除法和COUNT总是导致1?

时间:2017-01-09 16:40:44

标签: sql postgresql

我简化了这一点,因为文字数据非常庞大,但一个非常简单的例子就足够了。我正在进行一项查询,因为大量的数据,我希望一次性完成一些聚合而不是很多步骤。

我有两张桌子

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

这个例子非常简单,但实际情况要大得多。我确信有办法做到这一点,我只是不确定现在是什么。

1 个答案:

答案 0 :(得分:1)

您正在尝试计算不同的行,但不使用count(distinct ...)

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

注意,表现不是很好