我的桌子上有这样的记录:
+------+------+
| ID | name |
+------+------+
| 1 | A |
| 2 | B |
| 3 | C |
| 4 | A |
| 5 | B |
| 6 | A |
| 7 | A |
| 8 | A |
+------+------+
我需要在上次从不同的值更新后获取A的值,例如此处它将是ID为6的行。
答案 0 :(得分:3)
尝试此查询(MySQL语法):
select min(ID)
from records
where name = 'A'
and ID >=
(
select max(ID)
from records
where name <> 'A'
);
插图:
select * from records;
+------+------+
| ID | name |
+------+------+
| 1 | A |
| 2 | B |
| 3 | C |
| 4 | A |
| 5 | B |
| 6 | A |
| 7 | A |
| 8 | A |
+------+------+
- 运行查询:
+---------+
| min(ID) |
+---------+
| 6 |
+---------+
答案 1 :(得分:1)
使用Lag function ...
SELECT Max([ID])
FROM (SELECT [name], [ID],
Lag([name]) OVER (ORDER BY [ID]) AS PrvVal
FROM tablename) tbl
WHERE [name] = 'A'
AND prvval <> 'A'
在线演示:http://www.sqlfiddle.com/#!18/a55eb/2/0
如果你想获得整行,你可以这样做......
SELECT Top 1 *
FROM (SELECT [name], [ID],
Lag([name]) OVER (ORDER BY [ID]) AS PrvVal
FROM tablename) tbl
WHERE [name] = 'A' AND prvval <> 'A'
ORDER BY [ID] DESC
答案 2 :(得分:1)
下面的ANSI SQL在前一个id上使用自联接。
where子句获取的名称与之前的名称不同。
ID+1
它应该适用于大多数RDBMS,包括MS Sql Server。
请注意,delete [] a;
假设ID之间没有间隙。