简体   繁体   English

如何在 Oracle 中的相同日期/时间 DB 列之间减去

[英]How to substract between same date/time DB column in Oracle

Oracle SQL In the table there are status given to the each row(arrived, ExamCompleted, VitalsTaken, discharged...)where we track information about patients in the hospital. Oracle SQL 在表格中,每一行都有状态(到达、考试完成、生命体征、出院...),我们在其中跟踪有关医院患者的信息。 It is required to find the number of hours patient spent inside the hospital.需要找到患者在医院内度过的小时数。 How can I substract one column with itself where status are different.如何在状态不同的情况下减去一列。

patient_id     |      status         |  created_on
7654           |      arrived        |  2022-09-18 07:22:46
7654           |    examCompleted    |  2022-09-18 09:35:26
7654           |      vitalsTaken    |  2022-09-20 02:41:55
7654           |      discharged     |  2022-09-20 07:42:33

I need to substract arrived status date/time from discharged status date/time Table have many other columns but these are the ones I need to work with.我需要从出院状态日期/时间中减去到达状态日期/时间表还有许多其他列,但这些是我需要使用的列。 If there are null recorded for a created_on column (for few rows) how can I ignore that particular row while showing data.如果为 created_on 列(几行)记录了 null,我如何在显示数据时忽略该特定行。

Desired result is something like期望的结果类似于

patient_id     |         timeSpent
7654           |         48:19:13     

Thank you in advance先感谢您

Do a self join on the database table.对数据库表进行自联接。 The total time would be the value of column CREATED_ON when the STATUS is discharged minus the value of CREATED_ON when the STATUS is arrived for a given PATIENT_ID.总时间将是 STATUS释放时 CREATED_ON 列的值减去给定 PATIENT_ID到达STATUS 时 CREATED_ON 的值。 The below SQL gives the result as a number of hours.下面的 SQL 给出了以小时数表示的结果。

select A.PATIENT_ID
      ,(B.CREATED_ON - A.CREATED_ON) * 24 as STAY
  from PATIENTS A
  join PATIENTS B
    on A.PATIENT_ID = B.PATIENT_ID
 where A.STATUS = 'arrived'
   and B.STATUS = 'discharged'

Refer to this db<>fiddle参考这个db<>fiddle
Also refer to: https://asktom.oracle.com/Misc/DateDiff.html另请参阅: https://asktom.oracle.com/Misc/DateDiff.html

Correct??正确的?? That what you expected?那是你所期望的?

SELECT DISTINCT patient_id,
                MAX(created_on) OVER(PARTITION BY patient_id) - MIN(created_on) OVER(PARTITION BY patient_id)
  FROM PATIENTS 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM