SQL - 基于时间戳和ID

时间:2017-09-15 09:25:24

标签: sql

改变我的整个问题,因为我收到很多关于发布图片的投诉。我还添加了一个与我的情况更相似的代码。我很抱歉我是新手,我尽量让你尽可能轻松。

我使用IBM DB2 DBMS

我有一个查询,它选择了许多总是有ID(应该是唯一的)记录(消息),状态(错误,已完成)和时间戳。我的查询如下;

select *
 from  tableone tr, tabletwo ms
 where ms.TS BETWEEN '2017-09-15 00:00:00.000' and '2017-09-16 00:00:00.000'
 and ms.ID=tr.ID
 and ms.STATUS in ('ERROR','COMPLETED')
 ORDER by tr.ID

ID对于一条消息是唯一的,消息可以在不同的时间戳上获得多个状态,这将导致多条记录作为上述查询的输出。

我希望只有包含唯一讯息和最新状态的记录。

我希望你们和女士们可以提前帮助,谢谢你们。

3 个答案:

答案 0 :(得分:1)

Postgres,Oracle,SQL Server:

with CTE as
(
select t1.*, row_number() over(partition by t1.ID order by t1.Timestamp desc) rn
from MyTable t1
where t1.STATUS in ('ERROR','COMPLETED')
)
select *
from CTE
where rn = 1

的MySQL

select t1.*
from MyTable t1
inner join
(
select t2.ID, max(t2.Timestamp) as MaxT
from MyTable t2
where t2.STATUS in ('ERROR','COMPLETED')
group by t2.ID
) x3
on x3.ID = t1.ID
and x3.MaxT = t1.Timestamp
where t1.STATUS in ('ERROR','COMPLETED')

答案 1 :(得分:0)

试试吧

select *
 from  table_name a,
 where a.STATUS in ('ERROR','COMPLETED')
 and a.TimeStamp = (select max(b.TimeStamp)
                     from  table_name b,
                     where a.ID=B.ID) 
 ORDER by a.ID

select *
 from  table_name a,
 where a.STATUS in ('ERROR','COMPLETED')
 and a.TimeStamp = (select Top(1) b.TimeStamp
                     from  table_name b,
                     where a.ID=B.ID
                     order by b.TimeStamp desc) 
 ORDER by a.ID

答案 2 :(得分:0)

以下是基于您的值的代码。

我撤消了你的身份证,只获得了数字。我通过新ID执行了row_number并对其进行了排序以获得最新的。

使用漂亮的ID:

select * from (
select *,ROW_NUMBER() over(partition by TrueID order by timestamp DESC) as RN 
from (
SELECT REVERSE(substring(reverse([ID]),1,2)) as TrueID
  ,[Status]
  ,[Timestamp]
 FROM [LegOgSpass].[dbo].[statustable])x
 )z where RN= 1

使用原始ID:

select * from (
select *,ROW_NUMBER() over(partition by ID order by timestamp DESC) as RN 
from (
SELECT ID
  ,[Status]
  ,[Timestamp]
FROM [LegOgSpass].[dbo].[statustable])x
)z where RN= 1
相关问题