2016-07-26 134 views
1

我有一個表person_id,timestampname。我試圖編寫一個查詢來獲取給定日期(在給定時區內)某個人的第一個時間戳。當然,我嘗試過使用FIRST_VALUE並在當天進行分區,但不知道爲什麼它不起作用。通過窗口函數獲取第一個時間戳

SELECT first_value("timestamp") OVER w, 
    date_trunc('day', "timestamp" AT TIME ZONE 'US/Central') 
FROM analytics_analyticsevent as ae 
WHERE person_id=3 
GROUP BY date_trunc('day', "timestamp" AT TIME ZONE 'US/Central') 
WINDOW w as (PARTITION BY date_trunc('day', "timestamp" AT TIME ZONE 'US/Central')) 

這給我的錯誤:

ERROR: column "ae.timestamp" must appear in the GROUP BY clause or be used in an aggregate function 
LINE 2: SELECT first_value("timestamp") OVER w, 
         ^

任何想法?

+0

您必須在group by中添加first_value(「timestamp」) –

回答

0

它看起來像一個經典top-n-per-group。通常人們使用ROW_NUMBER,如下所示:

SELECT 
    "timestamp" 
    ,dt 
FROM 
    (
     SELECT 
      "timestamp" 
      ,date_trunc('day', "timestamp" AT TIME ZONE 'US/Central') AS dt 
      ,ROW_NUMBER() OVER 
       (PARTITION BY date_trunc('day', "timestamp" AT TIME ZONE 'US/Central') 
       ORDER BY "timestamp") AS rn 
     FROM analytics_analyticsevent as ae 
     WHERE person_id=3 
    ) AS T 
WHERE 
    T.rn = 1;