2017-03-03 138 views
1

我有以下表格:从多个表中检索数据 - SQL

表搜索:

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 

每件产品可以在同一天之内多行。当天产品的购买总数=总和(total_sale)

我需要找出每件产品每天的购买比率,即购买数量/搜索次数。

为了参考,对于耐克上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 

......我在做什么错在这里?

回答

1

执行聚集之前的加入:

select p.product, p.sales, s.searches 
from (select p.date, p.product, sum(p.Total_sale) as sales 
     from db.purchases p 
     group by p.date, p.product 
    ) p join 
    (select s.date, s.product, count(*) as searches 
     from db.searches s 
     group by s.date, s.product 
    ) s 
    on p.date = s.date and p.product = s.product 
where p.date = '2017-01-01' and p.product = 'Nike'; 

注意:您可以移动where纳入子查询,提高性能。这将很容易推广到更多的日子和产品。

2

该联接已经与您的结果集相乘,您将在删除GROUP BY并使用*代替指定的字段时看到它。

select * 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' 

你不需要加入表来计算购买率:

SELECT  
(select sum(t1.Total_sale) from db.purchases t1 where t1.date = '2017-01-01' and t1.product = 'Nike') 
/
(select count(t2.Search_ID) from db.searches t2 where t2.date = '2017-01-01' and t2.product = 'Nike') 
1

问题是您要加入两个未汇总的表,因此每个“购买”行都与每个“搜索”行连接。因此,你的结果32994,其中来自702 X 49

正确的方式来实现所期望的结果与加盟将

select t1.product, t1.total_sales, t2.search_count 
from (
      select date, product, sum(total_sales) as total_sales 
      from db.purchases 
      group by date, product 
     ) t1 
join (
      select date, product, count(search_id) as search_count 
      from db.searches 
      group by date, product 
     ) t2 
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;