我的表格如下所示:
ID |日期| X |国旗|
1 | 1/1/16 | 2 | 0
2 | 1/1/16 | 0 | 0
3 | 1/1/16 | 0 | 0
1 | 2/1/16 | 0 | 0
2 | 2/1/16 | 1 | 0
3 | 2/1/16 | 2 | 0
1 | 3/1/16 | 2 | 0
2 | 3/1/16 | 1 | 0
3 | 3/1/16 | 2 | 0
我正在努力使其在PREVIOUS月份中如果X = 2则填充标志。因此,它应该是这样的:
ID |日期| X |国旗|
1 | 1/1/16 | 2 | 0
2 | 1/1/16 | 0 | 0
3 | 1/1/16 | 0 | 0
1 | 2/1/16 | 2 | 1
2 | 2/1/16 | 1 | 0
3 | 2/1/16 | 2 | 0
1 | 3/1/16 | 2 | 1
2 | 3/1/16 | 1 | 0
3 | 3/1/16 | 2 | 1
我在SQL中使用它:
`select ID, date, X, flag into Work_Table from t
(
Select ID, date, X, flag,
Lag(X) Over (Partition By ID Order By date Asc) As Prev into Flag_table
From Work_Table
)
Update [dbo].[Flag_table]
Set flag = 1
where prev = '2'
UPDATE t
Set t.flag = [dbo].[Flag_table].flag FROM T
JOIN [dbo].[Flag_table]
ON t.ID= [dbo].[Flag_table].ID where T.date = [dbo].[Flag_table].date`
但是我不能在Bigquery中这样做。有什么想法吗?
答案 0 :(得分:2)
以下是BigQuery Standard SQL
#standardSQL
SELECT id, dt, x,
IF(LAG(x = 2) OVER(PARTITION BY id ORDER BY dt), 1, 0) flag
FROM `project.dataset.work_table`
您可以使用问题中的虚拟数据进行测试/播放
#standardSQL
WITH `project.dataset.work_table` AS (
SELECT 1 id, '1/1/16' dt, 2 x, 0 flag UNION ALL
SELECT 2, '1/1/16', 0, 0 UNION ALL
SELECT 3, '1/1/16', 0, 0 UNION ALL
SELECT 1, '2/1/16', 0, 0 UNION ALL
SELECT 2, '2/1/16', 1, 0 UNION ALL
SELECT 3, '2/1/16', 2, 0 UNION ALL
SELECT 1, '3/1/16', 2, 0 UNION ALL
SELECT 2, '3/1/16', 1, 0 UNION ALL
SELECT 3, '3/1/16', 2, 0
)
SELECT id, dt, x,
IF(LAG(x = 2) OVER(PARTITION BY id ORDER BY dt), 1, 0) flag
FROM `project.dataset.work_table`
ORDER BY dt, id
结果为
Row id dt x flag
1 1 1/1/16 2 0
2 2 1/1/16 0 0
3 3 1/1/16 0 0
4 1 2/1/16 0 1
5 2 2/1/16 1 0
6 3 2/1/16 2 0
7 1 3/1/16 2 0
8 2 3/1/16 1 0
9 3 3/1/16 2 1