两个查询的LEFT OUTER JOIN条件?

时间:2014-07-24 18:28:00

标签: sql database postgresql

从2014年1月开始,我有以下两个查询来查找每周的综合浏览量和订单。

select productid,
EXTRACT (week from dt)as WEEK,
count(productid)as PageViews
from PageView
where client = 'XYZ'
and dt between '2014-06-01' and '2014-06-30'
GROUP BY WEEK, productid
ORDER BY WEEK asc;

select
count(distinct t.orderid),
EXTRACT(week from t.dt) AS WEEK
FROM Transaction t
where t.client = 'XYZ'
and t.dt between '2014-01-01' AND '2014-06-30'
GROUP BY WEEK
ORDER BY WEEK asc;

为了获得正确的数据,我需要创建一个条件,该条件与Transaction和PageView Tables中的周相匹配,例如来自PageView的Transaction from Week = Week。然而,我不清楚这种语法是什么样的。

做一个简单的

PageView pv LEFT OUTER JOIN Transaction t
ON pv.productid = t.productid 
AND EXTRACT(week from t.dt) = EXTRACT(week from pv.dt) 

未提供正确的输出(即网页浏览量和订单数量显着增加)。有人可以说明如何组合这两个查询两个得到一个所需的输出,这是来自PageView表的所有产品和按周分组的交易表中的相应订单

2 个答案:

答案 0 :(得分:1)

select week, pid, pageviews, orders
from
    (
        select
            date_trunc('week', dt) as week,
            productid as pid,
            count(productid) as pageviews
        from pageview
        where client = 'XYZ' and dt between '2014-06-01' and '2014-06-30'
        group by 1, 2
    ) pv
    full outer join
    (
        select
            date_trunc('week', dt) as week,
            product_id as pid,
            count(orderid) as orders
        from transaction
        where client = 'XYZ' and dt between '2014-01-01' and '2014-06-30'
        group by 1, 2
    ) t using (week, pid)
order by 1, 2

答案 1 :(得分:0)

我认为问题是ON pv.productid = t.productid AND EXTRACT(week from t.dt) = EXTRACT(week from pv.dt)

这不能在左连接上。 PV和T之间的ID可能匹配,但在某些情况下,周数可能为空。所以AND会消除左连接。

所以你必须首先加入ID,这样才能获得最终的笛卡尔。然后你需要过滤掉不匹配的周,但留下T.Null值。但是它假设t.dt不能为null如果它可以为null,则计数可能仍然是关闭的,具体取决于你想要的方式处理事务表日期中的空值。

此外,您可能需要使用内联视图(但我认为这有点过分)

SELECT * 
FROM
(select productid,
  EXTRACT (week from dt)as WEEK,
  count(productid)as PageViews
  from PageView
  where client = 'XYZ'
  and dt between '2014-06-01' and '2014-06-30'
  GROUP BY WEEK, productid) PV
LEFT JOIN (
  SELECT
  count(distinct t.orderid),
  EXTRACT(week from t.dt) AS WEEK
  FROM Transaction t
  where t.client = 'XYZ'
  and t.dt between '2014-01-01' AND '2014-06-30'
  GROUP BY WEEK) T
ON pv.productid = t.productid  --The gold is in this and the next line
WHERE (T.Week = PV.Week OR T.Week is null)  --don't forget this one.

我认为这不会起作用...... ON(PV.ProductID = T.productID和T.Week = PV.Week)  OR(PV.ProductID = T.ProductID AND T.Week为null)

因为T.Week尚未被评估,因为笛卡尔不会被生成。因此,为什么我认为它属于哪里。