【问题标题】:SQl query to subtract two rows for the same id and populate the difference in a new columnSQl 查询以减去相同 id 的两行并将差异填充到新列中
【发布时间】:2018-05-15 05:07:36
【问题描述】:

这是我的输入表。我正在尝试填充表格,如下面的输出所示。请您帮我处理 SQL Server 中的 SQL 查询。

在table1中,ID是唯一的,每个ID都有timein和timeout。

表 2 表示关于 table1 中的 ID 在 timein 和 timeout 之间的更详细的操作。但是这个表只是有时间。使用表 1 和表 2 必须用实际时间(以分钟为单位)填充输出表。

输出表 row1 等于 table1 row1 以分钟为单位的时间差异作为实际时间

输出表 row2 等于 table2 row1 和 table2 row2 timein 作为 timeout 和 time diff 以分钟作为实际时间

输出表 row3 等于 table2 row2 和 table2 row3 timein 作为 timeout 和 time diff 以分钟作为实际时间

输出表 row4 等于 table2 row3 和 table1 row1 超时作为 timeout 和 time diff 以分钟为实际时间。

表 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

【问题讨论】:

  • 你可能想要更好地解释你的逻辑,以及你如何得到输出。

标签: sql sql-server


【解决方案1】:

需要在table2中添加一列,以便进行left join

 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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多