我有以下表格:
表搜索:
Date Product Search_ID
2017-01-01 Nike 101
2017-01-01 Reebok 292
2017-01-01 Nike 103
2017-01-01 Adidas 385
2017-01-02 Nike 284
餐桌采购
Date Product Total_sale
2017-01-01 Adidas 4
2017-01-01 Nike 1
2017-01-01 Adidas 2
2017-01-02 Nike 3
每个产品在同一天内可以有多行。当天购买产品的总次数=总和(总销售额)
我需要找到每天每种产品的购买比例,即购买次数/搜索次数。
供nike on参考 2017-01-01
,搜索总数为 702
而总购买数量 47
,给出了4的购买比例 7/702 = 0.0669
我试过:
select t1.product, sum(t1.Total_sale), count(t2.Search_ID)
from db.purchases t1 join db.searches
on t1.date = t2.date and t1.product = t2.product
where t1.date = '2017-01-01' and t1.product = 'Nike'
group by t1.product, t1.date
;
这给了我一个奇怪的结果:
product | sum | count
----------+-------+-------
Nike | 32994 | 32994
... 我做错什么了?
3条答案
按热度按时间z6psavjg1#
联接已使您的结果集成倍增加,当您删除group by并使用*而不是指定的字段时,您将看到它。
您不需要联接表来计算购买比率:
lzfw57am2#
在联接之前进行聚合:
注意:您可以移动
where
进入子查询,以提高性能。这将很容易推广到更多的日子和产品。nzk0hqpo3#
问题是您要连接两个未聚合的表,因此每个“购买”行都与每个“搜索”行相连接。所以你的结果是32994,它来自702x49。
使用连接实现所需结果的正确方法是