有了我的数据,我让个人在不同的日期多次进行评估。它看起来像这样:
╔════════╦═══════════╦═══════════╦═══════╗
║ Person ║ ID Number ║ Date ║ Score ║
║ John ║ 134 ║ 7/11/2013 ║ 18 ║
║ John ║ 134 ║ 8/23/2013 ║ 16 ║
║ John ║ 134 ║ 9/30/2013 ║ 16 ║
║ Kate ║ 887 ║ 2/28/2013 ║ 21 ║
║ Kate ║ 887 ║ 3/16/2013 ║ 19 ║
║ Bill ║ 990 ║ 4/18/2013 ║ 15 ║
║ Ken ║ 265 ║ 2/12/2013 ║ 23 ║
║ Ken ║ 265 ║ 4/25/2013 ║ 20 ║
║ Ken ║ 265 ║ 6/20/2013 ║ 19 ║
║ Ken ║ 265 ║ 7/15/2013 ║ 19 ║
╚════════╩═══════════╩═══════════╩═══════╝
我希望它在最后有另一列,用于计算自该人第一次评估以来的天数。如果这更容易的话,我也会选择自上次对该人进行评估以来的天数。
理想情况下,它看起来像这样:
╔════════╦═══════════╦═══════════╦═══════╦══════════════════╗
║ Person ║ ID Number ║ Date ║ Score ║ Days Since First ║
║ John ║ 134 ║ 7/11/2013 ║ 18 ║ 0 ║
║ John ║ 134 ║ 8/23/2013 ║ 16 ║ 43 ║
║ John ║ 134 ║ 9/30/2013 ║ 16 ║ 81 ║
║ Kate ║ 887 ║ 2/28/2013 ║ 21 ║ 0 ║
║ Kate ║ 887 ║ 3/16/2013 ║ 19 ║ 16 ║
║ Bill ║ 990 ║ 4/18/2013 ║ 15 ║ 0 ║
║ Ken ║ 265 ║ 2/12/2013 ║ 23 ║ 0 ║
║ Ken ║ 265 ║ 4/25/2013 ║ 20 ║ 72 ║
║ Ken ║ 265 ║ 6/20/2013 ║ 19 ║ 128 ║
║ Ken ║ 265 ║ 7/15/2013 ║ 19 ║ 153 ║
╚════════╩═══════════╩═══════════╩═══════╩══════════════════╝
我使用的是 Microsoft SQL Server 2008
最佳答案
select *
, datediff(day, min(Date) over (partition by [ID Number]), Date)
from YourTable
Live example at SQL Fiddle.
关于SQL:计算不同行中一列日期之间的天数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17303755/