我需要帮助编写此查询以获取类型为401的所有记录,除非最新记录类型为400. ID 16是一个让我失望的记录示例。我确信这很容易而且我在想它但是我已经坚持了几天了。请帮忙。
PK ID Type Changeddate
1 10 400 9/30/15 20:08
2 11 401 10/7/15 18:55
3 11 401 10/7/15 18:55
4 12 400 10/9/15 20:08
5 12 400 10/9/15 20:08
6 13 401 10/14/15 14:12
7 13 401 10/14/15 14:12
8 13 400 10/15/15 15:06
9 13 400 10/15/15 15:06
10 14 401 10/26/15 17:08
11 14 401 10/26/15 17:08
12 15 401 10/29/15 3:48
13 15 401 10/29/15 3:48
14 15 400 10/29/15 19:52
15 16 400 12/29/15 13:04
16 16 400 12/29/15 13:04
17 16 401 12/29/15 13:04
18 16 401 12/29/15 13:04
19 16 400 12/29/15 13:42
20 16 400 12/29/15 13:42
答案 0 :(得分:1)
对于SQL Server,您可以使用last_value
窗口函数:
select *
from (
select *
, last_value(Type) over (
partition by ID
order by Changeddate
rows between unbounded preceding and unbounded following)
as last_type
from YourTable yt1
where Type in (400, 401)
) sub
where last_type <> 400