左连接充当内连接?

时间:2014-07-12 02:30:14

标签: sql postgresql aggregate-functions outer-join

我有以下查询:

   SELECT DISTINCT t.productid as Prod_id,
   EXTRACT(week from t.dt) as WEEK,
   COUNT(pv.productid) as PageViews,
   COUNT(t.productid) as orders, 
   COUNT(t.productid)/COUNT(DISTINCT(pv.loadid)) as Conversion,
   AVG(t.price) avg_price,
   MAX(pv.numreviews) max_numreviews,
   MIN(pv.numreviews) min_numreviews,
   AVG(pv.numreviews) avg_numreviews,
   COUNT( DISTINCT pv.bvsid ) sessions
   FROM PageView pv LEFT OUTER JOIN Transaction t ON t.productid = pv.productid 
   AND t.dt BETWEEN '2014-06-06' AND '2014-06-18' AND ( lower(t.currency) = 'usd' OR lower(t.country) IN ('us', 'usa', 'united states') )
   WHERE pv.dt BETWEEN '2014-06-06' AND '2014-06-18'
   AND pv.client ='abc' AND lower(pv.type) = 'product'
   GROUP BY WEEK, Prod_id
   ORDER BY WEEK asc;

这使得PageViews和Orders的值相同,基本上只采用常见的产品。我想要正确的网页浏览量和订单价值,并且非常感谢您提供一些帮助。

1 个答案:

答案 0 :(得分:3)

表达式:

COUNT(pv.productid) as PageViews,
COUNT(t.productid) as orders, 

计算两个字段的非NULL值。如果它们相同,那么所有记录都匹配。但是,我怀疑你想要:

COUNT(pv.productid) as PageViews,
COUNT(distinct t.productid) as orders, 

此外,如果您拥有select distinct条款,则不应使用group by