![](/img/trans.png)
[英]subtract two rows and keep the latest row with the same ID in Sql Server
[英]SQl query to subtract two rows for the same id and populate the difference in a new column
這是我的輸入表。 我正在嘗試填充表,如下面的輸出所示。 您能幫我在SQL Server中進行SQL查詢嗎?
在表1中,ID是唯一的,並且每個ID都有一個timein和timeout。
表2表示在timein和timeout之間有關table1中ID的更詳細的操作。 但是這個表只是有時間。 如表1和表2所示,必須使用實際時間(以分鍾為單位)填充輸出表。
輸出表第1行等於表1第1行,以分鍾為單位的時間差作為實際時間
輸出表row2等於table2 row1和table2 row2 timein為超時,以分鍾為單位的時間差為實際時間
輸出表row3等於table2 row2和table2 row3 timein為超時,以分鍾為單位的時間差為實際時間
輸出表row4等於table2 row3和table1 row1超時為超時,以分鍾為單位的時間差為實際時間。
表格1
ID statusName1 Timein Timeout
--------------------------------------------
100 WITH M 9:00:00 10:15:00
101 WITH K 10:00:00 13:30:00
表2
key ID statusName2 Timein
----------------------------------
1 100 WITH A 9:05:00
2 100 WITH B 9:20:00
3 100 WITH C 9:45:00
4 101 WITH A 10:01:00
5 101 WITH D 10:11:00
我的輸出應該像
ID statusName TimeIn Timeout Actualtime
-------------------------------------------------------------
100 WITH M 9:00:00 10:15:00 75:00
100 WITH A 9:05:00 9:20:00 15:00
100 WITH B 9:20:00 9:45:00 25:00
100 WITH C 9:45:00 10:15:00 30:00
101 WITH K 10:00:00 13:30:00 210:00
101 WITH A 10:01:00 10:11:00 10:00
101 WITH D 10:11:00 13:30:00 199:00
您需要在table2中添加一列,以便進行左連接 。
ID statusName Actualtime TimeIn
100 WITH A 9:05:00 9:00:00
100 WITH B 9:20:00 9:00:00
100 WITH C 9:45:00 9:00:00
101 WITH M 10:01:00 10:00:00
101 WITH N 10:11:00 10:00:00
select table1.ID, table2.statusName,
table1.TimeIn, table1.Timeout, table2.Actualtime
from table1 LEFT JOIN
table2
ON table1.TimeIn= table2.TimeIn;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.