问题
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