2017-03-03 139 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;