2014-02-13 44 views
4

我有一个看起来像一些样本数据:(编辑:我没有SQL Server 2012中)仿效SQL Server和LINQ 2012滞后窗口功能

create table #base 
(pat_id int 
,admission_date date 
,discharge_date date 
) 
go 
insert into #base 
values 
(1, '2007-01-04', '2007-01-04'), 
(1, '2007-01-10', '2007-01-10'), 
(1, '2007-01-11', '2007-01-11'), 
(1, '2007-01-18', '2007-01-18'), 
(1, '2007-01-24', '2007-01-24'), 
(1, '2008-01-25', '2008-01-26'), 
(2, '2007-02-01', '2007-02-01'), 
(2, '2007-02-06', '2007-02-06'), 
(2, '2007-02-07', '2007-02-07'), 
(2, '2007-02-08', '2007-02-08') 

这里的SQL查询我想效仿与LINQ

;with cte 
as 
(
    select pat_id 
      ,admission_date 
      ,discharge_date 
      ,ROW_NUMBER() over(partition by pat_id order by admission_date asc) as rn 
    from #base 
) 
select firstCte.pat_id 
     ,firstCte.discharge_date as firstAdmitReference 
     ,secondCte.admission_date as dischargeReference 
     ,case when DATEDIFF(DAY,firstCte.discharge_date,secondCte.admission_date) <= 30 then 1 else 0 end Readmit 
from cte as firstCte 
inner join cte as secondCte 
     on firstCte.pat_id = secondCte.pat_id 
where firstCte.rn = secondCte.rn -1 

下面是查询的结果是什么样子:

create table #readmit_data 
(pat_id int 
,admission_date date 
,discharge_date date 
,within_x_days int 
) 
insert into #readmit_data(pat_id,admission_date,discharge_date,within_x_days) 
values 

(1, '2007-01-04', '2007-01-10', 1), 
(1, '2007-01-10', '2007-01-11', 1), 
(1, '2007-01-11', '2007-01-18', 1), 
(1, '2007-01-18', '2007-01-24', 1), 
(1, '2007-01-24', '2008-01-25', 0), 
(2, '2007-02-01', '2007-02-06', 1), 
(2, '2007-02-06', '2007-02-07', 1), 
(2, '2007-02-07', '2007-02-08', 1) 

在这个结果集中日的基本格式È数据是

patient ID dischargeDate nextVisitAdmitDate 

A 1在within_x_days列表示患者有重新接纳与他们的最后放电30天。理想情况下,30将是用户输入的变量。

LINQ中有什么样的构造可用于做到这一点?

+0

你想在LINQ to SQL查询中使用#Temp表吗?它不能做到。 – thepirat000

+0

是*#base *和*#temp *代码中的同一个表吗? – thepirat000

+0

@ thepirat000 #base和#temp是一样的。我实际上并不想查询临时表,我希望其他人能够快速查看问题,所以我添加了SQL脚本。 – wootscootinboogie

回答

3

LinqToSql没有类似于lag/lead/row_number的函数。

你根本无法做到这一点,最简单的方法是将SQL发送到机器上,然后在返回时将结果集映射到对象。