Why does my query involving division and COUNT always result in 1?

你说的曾经没有我的故事 提交于 2021-02-11 10:47:39

问题


I've simplified this down a bit since the literal data is pretty massive but a very simple example will suffice. I'm working on a query where because of the massive amount of data, I'm looking to do some aggregation in one shot instead of many many steps.

I have two tables

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

When I run the query

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

I get

4 | 4 | 1

When I'm looking for ...

3 | 4 | 1.3333333...

This example is extremely simplified, but the real case of this is massively larger. I'm sure there's a way to do this, I'm just not sure what that is right now.


回答1:


You are trying to count distinct rows, but not using a 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

Note, performance is not great



来源:https://stackoverflow.com/questions/41552730/why-does-my-query-involving-division-and-count-always-result-in-1

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!