我有一个名为Tbl_TickTock
的表:
ID | STATUS | DAYTIME |
----|-----------|---------------------------|
1 | unknown | 2017-03-30 13:30:30 |
1 | other | 2016-02-02 10:10:10 |
1 | active | 2015-01-01 00:00:00 |
2 | unknown | 2017-03-30 13:30:30 |
2 | other | 2016-02-02 10:10:10 |
2 | passive | 2015-01-01 00:00:00 |
3 | other | 2017-03-30 13:30:30 |
3 | active | 2016-02-02 10:10:10 |
3 | passive | 2015-01-01 00:00:00 |
4 | passive | 2017-03-30 13:30:30 |
4 | other | 2016-02-02 10:10:10 |
4 | active | 2015-01-01 00:00:00 |
5 | unknown | 2017-03-30 13:30:30 |
5 | passive | 2016-02-02 10:10:10 |
5 | active | 2015-01-01 00:00:00 |
6 | active | 2017-03-30 13:30:30 |
6 | passive | 2016-02-02 10:10:10 |
6 | active | 2015-01-01 00:00:00 |
DAYTIME数据类型为datetime
我需要两个不同的recorsets。
第一次查询
选择具有以下条件的所有行:
STATUS = 'passive'
STATUS ='active'
或STATUS = 'other'
此行比ID的最新行更新
STATUS = 'passive'
因此,
ID = 1:已排除,无'passive'
1 | unknown | 2017-03-30 13:30:30 |
1 | other | 2016-02-02 10:10:10 |
1 | active | 2015-01-01 00:00:00 |
ID = 4:已排除,'passive'
是最新的
4 | passive | 2017-03-30 13:30:30 |
4 | other | 2016-02-02 10:10:10 |
4 | active | 2015-01-01 00:00:00 |
ID = 4:排除,没有'active'
或'other'
比'passive'
更新
5 | unknown | 2017-03-30 13:30:30 |
5 | passive | 2016-02-02 10:10:10 |
5 | active | 2015-01-01 00:00:00 |
结果必须按ID,DAYTIME DESC
排序从上面的示例结果应该是:
ID | STATUS | DAYTIME |
----|-----------|---------------------------|
2 | unknown | 2017-03-30 13:30:30 |
2 | other | 2016-02-02 10:10:10 |
2 | passive | 2015-01-01 00:00:00 |
3 | other | 2017-03-30 13:30:30 |
3 | active | 2016-02-02 10:10:10 |
3 | passive | 2015-01-01 00:00:00 |
6 | active | 2017-03-30 13:30:30 |
6 | passive | 2016-02-02 10:10:10 |
6 | active | 2015-01-01 00:00:00 |
我知道从哪里开始,但我很失落所以跟随可能是没有希望的:
SELECT z1.*
FROM Tbl_TickTock z1
INNER JOIN
(SELECT MAX(daytime) as MAXdaytime )
FROM Tbl_TickTock) z2
ON z1.ID = z2.ID
AND ( here we put conditions? :
active is newer than passive OR
other is newer than passive )
第一次查询结束
第二次查询
与FIRST类似,但每个ID只返回一行。
必须填写与FIRST查询相同的条件:
STATUS = 'passive'
STATUS ='active'
或STATUS = 'other'
此行比ID的最新行更新
STATUS = 'passive'
必须按照以下顺序选择ID行
STATUS = 'active'
,请选择ID的最新行
其中STATUS = 'passive'
STATUS = 'other'
行来自FIRST查询条件的结果:
ID | STATUS | DAYTIME |
----|-----------|---------------------------|
2 | unknown | 2017-03-30 13:30:30 |
2 | other | 2016-02-02 10:10:10 | <--- Row to be returned
2 | passive | 2015-01-01 00:00:00 |
3 | other | 2017-03-30 13:30:30 |
3 | active | 2016-02-02 10:10:10 | <--- Row to be returned
3 | passive | 2015-01-01 00:00:00 |
6 | active | 2017-03-30 13:30:30 | <--- Row to be returned
6 | passive | 2016-02-02 10:10:10 |
6 | active | 2015-01-01 00:00:00 |
结果必须按ID,DAYTIME DESC
排序从上面的示例结果应该是:
ID | STATUS | DAYTIME |
----|-----------|---------------------------|
2 | other | 2016-02-02 10:10:10 |
3 | active | 2016-02-02 10:10:10 |
6 | active | 2017-03-30 13:30:30 |
第二次查询结束
任何帮助都非常感谢!