Calculate difference using nearest (oldest date) using same column

左心房为你撑大大i 提交于 2021-02-17 04:48:09

问题


I have the (simplified) database table A below which holds both the Mother Batch Purity Value and the Batch Puritys (all batches are made from the previous "Mother Batch".

I am trying to figure out how to pull out via SQL the Batch Purity and the Difference between the Batch Purity and the previous Mother Batch. The sample names always remain the same, but can be numerous batch numbers

Table A

Sample Name    |  Purity   |  Date (DD/MMM/YY)  
---------------+-----------+-----------------  
Mother Batch   |    100    |10-Oct-20  
   Batch 1     |    96     |11-Oct-20  
   Batch 2     |    94     |13-Oct-20  
Mother Batch   |    98     |14-Oct-20  
   Batch 1     |    94     |16-Oct-20  

Many thanks
Bob

回答1:


Use a conditional window functions:

select t.*,
       datediff(date,
                max(case when samplename like 'Mother%' then date end) over (order by date)
               ) as diff
from t;

EDIT:

In SQL Server, you would use:

       datediff(day,
                max(case when samplename like 'Mother%' then date end) over (order by date),
                date
               ) as diff


来源:https://stackoverflow.com/questions/64770015/calculate-difference-using-nearest-oldest-date-using-same-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!