【问题标题】:Left join acts as inner join?左连接充当内连接?
【发布时间】:2014-09-02 17:55:58
【问题描述】:

我有以下查询:

   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 的值相同,基本上只采用常见的 productid。我想要正确的 Pageviews 和 Orders 值,非常感谢您对此的帮助。

【问题讨论】:

  • SELECT DISTINCT productId... 应该是不必要的,因为你有一个匹配的GROUP BY。查询日期with an exclusive upper bound (<)Transaction 不应存储用户输入的数据:您应该规范化 currencycountry(不需要 LOWER(...))。使用WEEK(...) 将忽略索引;如果您使用范围表(通过日历表或作为查询的一部分生成),您可以使用一个。

标签: sql postgresql aggregate-functions outer-join


【解决方案1】:

表达式:

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

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

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

此外,当您有 group by 子句时,您不应使用 select distinct

【讨论】:

  • 感谢您的回复。做 Count(distinct t.productid) 只是给每个 productid 值'1',这是不正确的。
猜你喜欢
  • 1970-01-01
  • 2013-01-30
  • 1970-01-01
  • 1970-01-01
  • 2010-09-16
  • 2017-08-15
  • 2010-10-06
  • 2015-03-04
  • 2018-07-31
相关资源
最近更新 更多