SQL - 使用另一个表加入SubQuery两次

时间:2013-06-28 09:02:34

标签: sql join subquery

我正在尝试评估第2天和第7天的查询。如下所示,我重复自己,以便将结果放在同一数据集中。

SELECT count(distinct(koc.fbid)) AS players,
       avg(koc.level2) AS "average level2",
       avg(koc.level7) AS "average level7",
       koc.regdate AS date
FROM
  (SELECT koc.fbid AS fbid,
          max(evt2.level) AS "level2",
          max(evt7.level) AS "level7",
          koc.regdate AS regdate
   FROM
     (SELECT evt.utc_timestamp AS date,
             MAX(evt.l) AS LEVEL,
             evt.s AS fbid
      FROM "occ_test"."evt" "evt"
      WHERE date(TO_TIMESTAMP(evt.utc_timestamp)) >= '2013-06-01' AND (evt.n = 'LevelUp' OR evt.n = 'TutorialCompleted')
      GROUP BY evt.s, evt.utc_timestamp) evt2
   RIGHT JOIN
     (SELECT pros.utc_timestamp AS regdate,
             "pros"."s" AS "fbid",
      FROM "occ_test"."pros" "pros"
      INNER JOIN "occ_test"."pect" "pect" ON (("pros"."s" = "pect"."s") AND ("pros"."su" = "pect"."su"))
      JOIN "occ_test"."users" "users" ON ("pros"."s" = "users"."name")
      WHERE (pect.st1 = 'fbad' OR pect.st1 = 'du') AND date(TO_TIMESTAMP(pros.utc_timestamp)) >= '2013-06-01'
      GROUP BY pros.s, pect.st1, pect.st2, pros.utc_timestamp koc ON evt2.fbid = koc.fbid AND evt2.date <= koc.regdate + 1
   LEFT JOIN
     (SELECT evt.utc_timestamp AS date,
             MAX(evt.l) AS LEVEL,
             evt.s AS fbid
      FROM "occ_test"."evt" "evt"
      WHERE date(TO_TIMESTAMP(evt.utc_timestamp)) >= '2013-06-01' AND (evt.n = 'LevelUp' OR evt.n = 'TutorialCompleted')
      GROUP BY evt.s, evt.utc_timestamp evt7 ON evt7.fbid = koc.fbid AND evt7.date <= koc.regdate + 6
   GROUP BY koc.regdate,
            koc.fbid) koc
GROUP BY koc.campaign,
         koc.regdate

这是重复部分:(称为evt2和evt7)

 (SELECT evt.utc_timestamp AS date,
         MAX(evt.l) AS LEVEL,
         evt.s AS fbid
  FROM "occ_test"."evt" "evt"
  WHERE date(TO_TIMESTAMP(evt.utc_timestamp)) >= '2013-06-01' AND (evt.n = 'LevelUp' OR evt.n = 'TutorialCompleted')
  GROUP BY evt.s, evt.utc_timestamp)

我想知道有没有办法不写evt7并使用evt2作为“LEFT JOIN”,因为唯一的区别是在日期而不是1上加6。

如果你可以提供帮助,那就太棒了。 感谢

0 个答案:

没有答案