我需要一个SQL查询来基于未更改的列值仅获取最后一行。我该怎么办?
表:表1
ID LEVEL
1 1
2 1
3 2
4 4
5 3
6 3
7 4
8 5
9 3
10 3
我需要一个SQL查询,该查询可以为我提供包含级别3的最后一行,直到它保持不变为止。
例如
select * from table where level = 3 order by ID desc;
给予
10 3
9 3
6 3
5 3
我只想要
9 3
10 3
答案 0 :(得分:1)
例如:
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(ID SERIAL PRIMARY KEY
,LEVEL INT NOT NULL
);
INSERT INTO my_table VALUES
( 1,1),
( 2,1),
( 3,2),
( 4,4),
( 5,3),
( 6,3),
( 7,4),
( 8,5),
( 9,3),
(10,3);
SELECT MIN(id) range_start
, MAX(id) range_end
, level
FROM
( SELECT x.*
, CASE WHEN @prev=level THEN @i:=@i ELSE @i:=@i+1 END i
, @prev:= level
FROM my_table x
,( SELECT @prev:=null,@i:=0 ) vars
ORDER
BY id
) a
WHERE level = 3 -- optional
GROUP
BY level
, i
ORDER
BY range_start DESC
LIMIT 1;
+-------------+-----------+-------+
| range_start | range_end | level |
+-------------+-----------+-------+
| 9 | 10 | 3 |
+-------------+-----------+-------+