【发布时间】: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不应存储用户输入的数据:您应该规范化currency和country(不需要LOWER(...))。使用WEEK(...)将忽略索引;如果您使用范围表(通过日历表或作为查询的一部分生成),您可以使用一个。
标签: sql postgresql aggregate-functions outer-join