使用多个联接时,COUNT会返回双精度值

时间:2015-11-15 20:36:13

标签: sql database postgresql

当我运行此查询时,我得到了我想要的结果。

SELECT 
referer_trackings.cookie_first_url AS url,
sum(purchases.price) AS sales, 
count(purchases.id) AS volume
FROM purchases
JOIN referer_trackings 
ON referer_trackings.trackable_id = purchases.id
JOIN items
ON purchases.item_id = items.id
WHERE items.seller_id = '39'
AND referer_trackings.trackable_type = 'Purchase'
AND purchases.workflow_state = 'payment_successful'
GROUP BY referer_trackings.cookie_first_url

返回:

url             sales          volume
======================================
UrlName1.com    8743           332
UrlName2.com    234            123
UrlName3.com    2352           2345

这是正确的,但我也将登录页面视图存储在另一个单独的表中,因为我真正需要的是:

url             sales          volume       landing_page_views
===============================================================
UrlName1.com    8743           332          34563
UrlName2.com    234            123          52443
UrlName3.com    2352           2345         84563

要获得此结果,请运行此查询:

SELECT 
referer_trackings.cookie_first_url AS url,
sum(purchases.price) AS sales, 
count(purchases.id) AS volume,
COUNT(DISTINCT product_landing_page_views.id) AS ulpvs
FROM purchases
JOIN referer_trackings 
ON referer_trackings.trackable_id = purchases.id
JOIN items
ON purchases.item_id = items.id
JOIN product_landing_page_views
ON product_landing_page_views.item_id = items.id
WHERE items.seller_id = '39'
AND referer_trackings.trackable_type = 'Purchase'
AND purchases.workflow_state = 'payment_successful'
GROUP BY referer_trackings.cookie_first_url

这会导致数据看起来翻倍并且比实际计数多。我知道这是因为调用

JOIN product_landing_page_views
ON product_landing_page_views.item_id = items.id

为结果添加行,从而使计数倍增。

所以我的问题是:如何确保在加入product_landing_page_views表时查询仍会产生正确的计数?

1 个答案:

答案 0 :(得分:0)

试试这个: -

SELECT 
referer_trackings.cookie_first_url AS url,
sum(purchases.price) AS sales, 
count(purchases.id) AS volume,
product_landing_page_views.ulpvs
FROM purchases
JOIN referer_trackings 
ON referer_trackings.trackable_id = purchases.id
JOIN items
ON purchases.item_id = items.id
JOIN (SELECT item_id, count(*) as ulpvs from product_landing_page_views GROUP BY item_id) as product_landing_page_views
ON product_landing_page_views.item_id = items.id
WHERE items.seller_id = '39'
AND referer_trackings.trackable_type = 'Purchase'
AND purchases.workflow_state = 'payment_successful'
GROUP BY referer_trackings.cookie_first_url

(这是假设我正确理解你桌子的结构。如果没有道歉)。