2016-02-12 51 views
0

我在Redshift上使用postgres。我有一個查詢這是這樣的:基於來自內部查詢的組合的子集設置

SELECT EXTRACT(year from created_at) AS CustomYear, 
      client_ip, 
      member_id, 
      COUNT(*) AS Views 
     FROM ads.fbs_page_view_staging 
     WHERE member_id = 2 
     GROUP BY CustomYear, 
       client_ip, 
       member_id 
     HAVING COUNT(*) = 1 
     ORDER BY CustomYear 

在這裏,我選擇的client_ipmember_id其中Views是組合1.我現在想採取的client_ipmember_id這些組合和子集整個表ads.fbs_page_view_staging只有這樣的組合。

如果只有一個專欄中,我想在子集,說client_ip,我已經寫了下面的查詢,並得到了結果:

SELECT EXTRACT(year FROM created_at) AS CustomYear, 
     COUNT(*) 
FROM ads.fbs_page_view_staging 
WHERE member_id = 2 
AND client_ip IN (SELECT client_ip 
        FROM ((SELECT EXTRACT(year from created_at) AS CustomYear, 
            client_ip, 
            member_id, 
            COUNT(*) 
          FROM ads.fbs_page_view_staging 
          WHERE member_id = 2 
          GROUP BY CustomYear, 
            client_ip, 
            member_id 
          HAVING COUNT(*) = 1 
          ORDER BY CustomYear))) 
GROUP BY customyear 
ORDER BY customyear 

注意,在外部查詢,我子集化基礎的在client_ip。但是,我如何在列的組合上對錶進行分組?

任何幫助將不勝感激。

+0

我認爲這可能會有所幫助,如果您能準確描述您想要在最終結果中看到哪些行。我知道你想要一個基於子查詢的子集,但是你能更準確地描述它嗎? – Bampfer

回答

0

而不是subquerying,嘗試直接加入到您的查詢結果。這樣你可以指定多個標準。

這裏是(草案)SQL來選擇匹配的子查詢中找到的行是IP /成員對(即對於一些年以前,有針對IP &成員只有一個視圖。)

SELECT distinct client_ip, member_id 
FROM ads.fbs_page_view_staging Staging 
INNER JOIN (SELECT EXTRACT(year from created_at) AS CustomYear, 
     client_ip, 
     member_id, 
     COUNT(*) AS Views 
    FROM ads.fbs_page_view_staging 
    WHERE member_id = 2 
    GROUP BY CustomYear, 
      client_ip, 
      member_id 
    HAVING COUNT(*) = 1) SingularViews 
ON SingularViews.client_ip=Staging.client_ip 
AND SingularViews.member_id=Staging.member_id 
ORDER BY Staging.client_ip, Staging.member_id 

我不確定我是否已經正確捕獲了您的查詢的意圖,但是如果不希望您可以適應該技術。

+0

非常感謝您的回答。我沒有得到我期待的結果。當我每年彙總(計數)結果時,會得到一組結果,這些結果與我在加入內部子查詢結果後每年彙總(計數)結果後得到的結果不同。 – Patthebug