如何通过加入两个表来获得日期差异?

时间:2016-03-15 06:34:28

标签: sql-server linq date

我有数据表,如

Table1:

id  Name   date
--------------
1   xxx  01/01/2015
2   yyy  01/02/2015
3   aaa  02/03/2015

Table 2:

id Name   date
--------------
 1  xxx    07/01/1015
 2  xxx    09/01/2015
 3  yyy    05/02/2015
 4. aaa    04/03/2015

我试图通过连接两个表来获取日期差异。但是,当第一次出现名称时,我必须通过使用Table1来获得差异。如果发生名称的重复值,则表示仅通过使用Table2就可以获得差异。请以(dd / mm / yyyy)格式记下日期 结果应该如下所示,

 Name  DateDifference

 xxx    6  (07/01/2015 - 01/01/2015)
 xxx    2  (07/01/2015 - 09/01/2015)
 yyy    4  (01/02/2015- 05/02/2015)
 aaa    2   (02/03/2015 -04/03/2015)

我试过的SQL查询是

SELECT    s.spidername,   
        T1.Date, 
        MIN(T2.Date) AS Date2, 
        DATEDIFF("D", T1.Date, MIN(T2.Date)) AS DaysDiff

FROM    Spider_DailyJobCount T1
        LEFT JOIN Spider_DailyJobCount T2
            ON T1.SpiderName = T2.SpiderName
            AND T2.Date > T1.Date
join spider s on s.spidername = t1.spidername
 where //Condition
GROUP BY   T1.Date,s.spidername

我试过的LINQ查询是,

var query = (from item1 in Table1
                join item2 in Table1 on item1.Name equals item2.SpiderName
                where item2.Date > item1.Date
                join origin in Table2 on item1.Name equals origin.Name
                where // condition
                group new { item1,item2 } by new {  item1.Name,item1.Date } into grp
                select new
                {                   

                    DayDiff = DbFunctions.DiffDays(grp.Key.Date, grp.Min(d => d.item2.Date)),
                }
                ).ToList();

我尝试过这些东西,但无法获得所需的输出。我只尝试过Table2值。我真的不知道如何从Table1中获取第一次出现的值。 任何帮助或建议表示赞赏。 在此先感谢!

1 个答案:

答案 0 :(得分:2)

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获取日期差异