SQL:如何在没有GROUP BY的情况下计算值的总和

时间:2018-01-08 13:57:57

标签: sql google-bigquery

我有下表:

visitorId    visitNumber   DATE         
1            1             20180101     
1            2             20180101   
1            3             20180105    
2            1             20171230  
2            2             20180106    

我想要回归的是:

visitorId    totalVisits   max_visits_in_1_day  
1            3             2                       
2            2             1                       

我设法在没有使用max_visits_in_1_day的情况下完成所有工作:

SELECT visitorId, 
MAX(visitNumber) - MIN(visitNumber) + 1 as totalVisits, 
GROUP BY visitorId

我需要做的是改进代码,以便添加max_visits_in_1_day。像MAX(COUNT(GROUP BY(DATE)))

这样的东西

我首先尝试添加MAX(COUNT(DATE)),但这会聚合所有日期,并且实际上并未查找最大唯一日期。从某种意义上说,我需要在DATE进行GROUP BY,然后计算总和。

我尝试添加GROUP BY visitorId, DATE但这会创建额外的行。

2 个答案:

答案 0 :(得分:2)

你必须采取以下两个步骤:

SELECT visitorId, SUM(perDay) AS totalVisits, MAX(perDay) AS max_visits_in_1_day
FROM
(SELECT visitorId, COUNT(visitNumber) AS perDay, DATE
FROM myTable
GROUP BY visitorId, DATE) A
GROUP BY visitorId

答案 1 :(得分:1)

您可以尝试以下查询 -

SELECT visitorId
      ,COUNT(visitNumber) totalVisits
      ,mv1d.count max_visits_in_1_day
FROM YOUR_TABLE YT
INNER JOIN (SELECT visitorId, MAX(COUNT(DATE)) count
            FROM YOUR_TABLE YT1)
ON YT.visitorId = YT1.visitorId
GROUP BY visitorId