2017-09-15 125 views
-2

更改我的整個問題,因爲我收到很多關於發佈圖像的抱怨。我還添加了一個更類似於我的情況的代碼。我很抱歉我是新手,所以我儘量讓你儘可能簡單。SQL - 基於時間戳和ID的最新記錄

我使用IBM DB2數據庫管理系統

我有選擇了很多紀錄(消息)總是有一個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是唯一的一個消息,一個消息可以得到在不同的時間標記,這將導致在多個記錄作爲上述查詢的輸出多個狀態。

我希望只有具有獨特信息和最新獲得狀態的記錄。

我希望你們和gals可以提前幫助,謝謝。

+1

這裏大部分人都希望格式化的文本,而不是圖像。 (或者,更糟糕的是,指向圖像的鏈接。) – jarlh

+0

語法錯誤。在WHERE之前刪除那個逗號。 – jarlh

+1

你的dbms是否真的接受1作爲表別名?你使用哪個dbms? – jarlh

回答

1

Postgres的,甲骨文,SQL服務器:

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') 
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 
0

這裏是根據你的價值觀的代碼。

I反轉您的ID以獲取唯一號碼。我用新的ID做了一個row_number,並將它排序以獲得最新的ID。

漂亮的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