如何在特定日期之间的日期进行SQL连接?

时间:2016-10-18 10:55:39

标签: google-bigquery

这可能非常难或非常简单,我不知道哪个但是我被卡住了。

如何加入特定日期之间发生的数据?我该怎么写?棘手的是每一行都有不同的时间段,每个用户都有一个独特的时期。例如:

表A. enter image description here

表B

enter image description here

表C(我想要的那个)

enter image description here

如果有人想知道

,我正在使用Google BigQuery

1 个答案:

答案 0 :(得分:4)

以下是BigQuery Standard SQL(请参阅Enabling Standard SQL

SELECT 
  a.User_Id, Start_date, End_Date, 
  (SELECT IFNULL(SUM(clicks),0) FROM TableB WHERE user_Id = a.User_Id 
  AND date BETWEEN Start_date AND End_date) AS Clicks_from_tableB
FROM TableA AS a
ORDER BY user_Id

SELECT 
  a.User_Id, Start_date, End_Date, 
  SUM(IFNULL(clicks, 0))  AS Clicks_from_tableB
FROM TableA AS a
LEFT JOIN TableB AS b
ON a.User_Id = b.User_Id
AND b.date BETWEEN Start_date AND End_date
GROUP BY 1, 2, 3
ORDER BY user_Id