如何对有序行进行分组?

时间:2018-02-21 17:22:28

标签: sql postgresql amazon-redshift

我在postgres下面的表格

| col1 | col2                |
|:----:|---------------------|
| A    | 2018-02-21 01:00:01 |
| A    | 2018-02-21 13:00:01 |
| A    | 2018-02-21 14:00:01 |
| B    | 2018-02-21 16:00:01 |
| B    | 2018-02-22 06:00:01 |
| A    | 2018-02-22 10:00:01 |
| A    | 2018-02-23 11:00:01 |
| C    | 2018-02-24 15:00:01 |

我想要这样的输出

| col1 | col2                |
|:----:|---------------------|
| A    | 2018-02-21 01:00:01 |
| B    | 2018-02-21 16:00:01 |
| A    | 2018-02-22 10:00:01 |
| C    | 2018-02-24 15:00:01 |

如何实现此输出?

1 个答案:

答案 0 :(得分:2)

可以使用lag来获取前一个col1值并将其与当前行的值进行比较。

select col1,col2
from (select col1,col2,lag(col1) over(order by col2) as prev_col1
      from tbl
     ) t
where prev_col1 is null or prev_col1<>col1
相关问题