我有如下示例数据。
width
现在我希望结果应该是这样的:
+---------+------------+--------+
| user id | sequence | Action |
|---------|------------|--------|
| 12345 | 1 | Run |
| 12345 | 2 | Sit |
| 12345 | 3 | Sit |
| 12345 | 4 | Run |
| 12345 | 5 | Run |
| 12345 | 6 | Sit |
+---------+------------+--------+
应将序列#2和#3的行合并,将#4和#5的行合并。 我使用“按操作分组”将获得如下表所示的答案,但这不是我想要的:
+---------+---------+
| user id | Action |
|---------|---------|
| 12345 | Run |
| 12345 | Sit |
| 12345 | Run |
| 12345 | Sit |
+---------+---------+
如何实现SQL(我使用Google Bigquery)?
感谢一百万!
答案 0 :(得分:1)
下面是BigQuery标准SQL
#standardSQL
SELECT * EXCEPT(dup) FROM (
SELECT *, action = LAG(action, 1, '') OVER(PARTITION BY user_id ORDER BY sequence) AS dup
FROM `project.dataset.table`
)
WHERE NOT dup
如果要应用于您的问题的样本数据-输出为
Row user_id sequence action
1 12345 1 Run
2 12345 2 Sit
3 12345 4 Run
4 12345 6 Sit
答案 1 :(得分:0)
您可以使用窗口函数:其想法是将每行的操作与“上一个”操作进行比较,并在值更改的行上进行过滤:
select *
from (
select t.*, lag(action) over(partition by user_id order by sequence) lag_action
from mytable t
) t
where action <> lag_action or lag_action is null