添加行号 - 使用max() - BigQuery

时间:2017-04-11 10:39:08

标签: google-bigquery

我发现这个解决方案here非常好用,但是我需要在我的结果中添加一个max()函数,以便只报告最大的访问次数,同时仍然按照带有降序行号的fullvisitorID进行分组

这是我的查询目前的样子,

Current result:
Row row_number  fullvisitorID   visitnumber  
1   1   7798230386693640077 15187    
2   2   7798230386693640077 15186    
3   3   7798230386693640077 15185    
4   4   6990057712104307809 15133    
5   5   1693270353484553172 12519    
6   6   1693270353484553172 12518

Desired result:
Row row_number  fullvisitorID   visitnumber  
1   1   7798230386693640077 15187    
2   2   6990057712104307809 15133
3   3   1693270353484553172 12519 
4   4   2117072763989389740 11607
5   5   2336272987018271381 10487    
6   6   1563891584913132229  9927

任何关于如何引入max()函数的帮助都非常感激。

ionic-framework version 2

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT 
   row_number () over() row_number,
   fullvisitorID,
   maxVisitNumber       
FROM (
        SELECT fullvisitorID, max(visitnumber) as maxVisitnumber,
        FROM [data]
        GROUP BY fullvisitorID
        ORDER BY maxVisitnumber DESC
)

也就是说,在获取行号之前,使用子查询计算每个fullVisitorId的最大visitNumber。

答案 1 :(得分:0)

尝试以下

SELECT
  ROW_NUMBER() OVER(ORDER BY visitnumber DESC) rownumber,
  fullvisitorID,
  visitnumber
FROM (
  SELECT 
    ROW_NUMBER() OVER(PARTITION BY fullvisitorID ORDER BY visitnumber DESC) pos,
    fullvisitorID,
    visitnumber,
  FROM (
    SELECT fullvisitorID, visitnumber, 
    FROM [data]
    GROUP BY fullvisitorID,visitnumber
  )
)
WHERE pos = 1
-- ORDER BY visitnumber DESC