我有一个数据集,我需要计算日期差异。我需要一个通用查询,因为数据集每天都会有所不同。
这是我的数据集
**Client Number : Status : StatusDate**
123456 Admit 2012-01-18
123456 Accepted 2012-01-15
123456 Offered 2012-01-10
567899 Admit 2012-01-11
567899 Accepted 2012-01-07
567899 Offered 2012-01-05
987342 Admit 2012-01-24
987342 Accepted 2012-01-24
987342 Offered 2012-01-21
以上是样本数据,正如我所说,数据将每日更改。对于特定的客户编号,将始终输入三个,如上所示,上面的顺序始终为三个状态。
我需要的是计算提供给接受和接受接受之间的天数。上面的结果集应如下所示。三栏
**ClientNumber : Date Diff Betw Offeres & Accepted : Date Diff Betw Accepted & Admited**
123456 5 Days 3 Days
567899 2 Days 4 Days
987342 3 Days 0 Days
我需要通用查询,正如我所说,每个客户编号都有三种状态。
提前致谢。
答案 0 :(得分:1)
你必须自我加入。这是一个通用的例子。
select t1.clientnumber, datediff(day, t1.statusdate, t2.statusdate) OfferToAccept
from yourtable t1 join yourtable t2 on t1.clientnumber = t2clientnumber
and t1.status = 'Offered' and t2.status = 'Accepted'
where whatever
对于你的问题中可能输入错误的另一个区间,这是类似的事情。它说“接受日期差异接受和接受”
答案 1 :(得分:0)
查询:
<强> SQLFIDDLEExample 强>
SELECT t1.[Client Number],
MAX(datediff(DAY, t1.statusdate, t2.statusdate)) [Offeres & Accepted],
MAX(datediff(DAY, t3.statusdate, t1.statusdate)) [Accepted & Admited]
FROM Table1 t1
LEFT JOIN Table1 t2 ON t1.[Client Number] = t2.[Client Number]
AND t1.status = 'Offered'
AND t2.status = 'Accepted'
LEFT JOIN Table1 t3 ON t1.[Client Number] = t3.[Client Number]
AND t1.status = 'Admit'
AND t3.status = 'Accepted'
GROUP BY t1.[Client Number]
结果:
| CLIENT NUMBER | OFFERES & ACCEPTED | ACCEPTED & ADMITED |
-----------------------------------------------------------
| 123456 | 5 | 3 |
| 567899 | 2 | 4 |
| 987342 | 3 | 0 |