计算与组内最小值的差异

时间:2016-06-28 06:17:29

标签: sql postgresql group-by aggregate

鉴于下表:

| id|    Date    |

| 1 | 04-01-2016 |
| 1 | 04-07-2016 |
| 1 | 04-09-2016 |
| 2 | 04-06-2016 |
| 2 | 04-03-2016 |
| 2 | 04-10-2016 |

我希望有一个列,其中包含每天与ID分组中最小日期之间的天数。

 id  |   date     |  day_count 
  ---+------------+------------
   1 | 04-01-2016 |     0 (days between 04-01-2016 and 04-01-2016)
   1 | 04-04-2016 |     3 (days between 04-04-2016 and 04-01-2016)
   1 | 04-08-2016 |     7 
   2 | 04-17-2016 |     14 (days between 04-017-2016 and 04-03-2016)
   2 | 04-03-2016 |     0
   2 | 04-10-2016 |     7

1 个答案:

答案 0 :(得分:2)

通过使用Window Function和Datediff我们可以实现以下结果

DECLARE @Table1  TABLE 
    (id int, date datetime)
;

INSERT INTO @Table1
    (id, date)
VALUES
    (1, '2016-04-01 05:30:00'),
    (1, '2016-04-04 05:30:00'),
    (1, '2016-04-08 05:30:00'),
    (2, '2016-04-03 05:30:00'),
    (2, '2016-04-17 05:30:00'),
    (2, '2016-04-20 05:30:00')
;

脚本

 select  *
,       datediff(day, min(Date) over (partition by [ID]), Date)Cnt
from    @Table1