如何将 sql 中的行按特定顺序分组
How to group rows in sql with particular order in bunch of sets
假设我有一个有 3 列的 table
one
two
three
x
LF
1
x
FI
2
x
LF
3
x
FI
4
x
FI
5
x
FI
6
x
LF
7
x
FI
8
x
LF
9
x
FI
10
x
LF
11
x
LF
12
x
LF
13
x
LF
14
x
FI
15
现在我想要的是将 'two' 列分组并取最低的 'third' 列值,这将给我输出
one
two
three
x
LF
1
x
FI
2
x
LF
3
x
FI
4
x
LF
7
x
FI
8
x
LF
9
x
FI
10
x
LF
11
x
FI
15
我怎样才能做到这一点?
您似乎想要更改的行。您可以使用 lag()
:
select one, two, three
from (select t.*,
lag(two) over (order by three) as prev_two
from t
) t
where prev_two is null or prev_two <> two;
假设我有一个有 3 列的 table
one | two | three |
---|---|---|
x | LF | 1 |
x | FI | 2 |
x | LF | 3 |
x | FI | 4 |
x | FI | 5 |
x | FI | 6 |
x | LF | 7 |
x | FI | 8 |
x | LF | 9 |
x | FI | 10 |
x | LF | 11 |
x | LF | 12 |
x | LF | 13 |
x | LF | 14 |
x | FI | 15 |
现在我想要的是将 'two' 列分组并取最低的 'third' 列值,这将给我输出
one | two | three |
---|---|---|
x | LF | 1 |
x | FI | 2 |
x | LF | 3 |
x | FI | 4 |
x | LF | 7 |
x | FI | 8 |
x | LF | 9 |
x | FI | 10 |
x | LF | 11 |
x | FI | 15 |
我怎样才能做到这一点?
您似乎想要更改的行。您可以使用 lag()
:
select one, two, three
from (select t.*,
lag(two) over (order by three) as prev_two
from t
) t
where prev_two is null or prev_two <> two;