且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何通过联接两个表来获得日期差?

更新时间:2023-02-03 16:18:52

t-sql解决方案

declare @Table1 table
(
    id  int,
    Name    varchar(3),
    date    date
)

declare @Table2 table
(
    id  int,
    Name    varchar(3),
    date    date
)

set dateformat dmy

insert into @Table1 select 1,   'xxx',  '01/01/2015'
insert into @Table1 select 2,   'yyy',  '01/02/2015'
insert into @Table1 select 3,   'aaa',  '02/03/2015'

insert into @Table2 select 1,  'xxx',    '07/01/2015'
insert into @Table2 select 2,  'xxx',    '09/01/2015'
insert into @Table2 select 3,  'yyy',    '05/02/2015'
insert into @Table2 select 4,  'aaa',    '04/03/2015'

-- Actual Query
; with cte as
(
    select  *, rn = row_number() over (partition by Name order by date)
    from
    (
        select * from @Table1 union all select * from @Table2
    ) t
)
select  c1.Name, c1.date, c2.date, diff = datediff(day, c1.date, c2.date)
from    cte c1
    inner join cte c2   on  c1.Name = c2.Name
                and c1.rn   = c2.rn - 1

简要说明:

  • 看起来您的要求实际上是查找2条记录之间的日期差异
  • 这就是UNION ALL的工作.它将两个表合并为一个
  • row_number()用于按日期升序为具有相同名称的行分配一个顺序编号
  • 下一步是通过INNER JOIN获取日期差异