使用LINQ模拟SQL Server 2012延迟窗口功能

时间:2014-02-13 19:58:44

标签: c# sql sql-server linq

我有一些示例数据:(编辑:我没有SQL Server 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')

这是我想用LINQ模拟的SQL查询

;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

within_x_days栏中的1表示患者最后一次出院30天后再次入院。理想情况下,30将是用户输入的变量。

LINQ中有哪种构造可用于此?

3 个答案:

答案 0 :(得分:3)

LinqToSql没有延迟/导致/ row_number的类似功能。

您根本无法做到这一点,最简单的方法是将SQL发送到计算机,然后在结束时将结果集映射到对象。

答案 1 :(得分:3)

Window To LINQ是.NET扩展功能的库

答案 2 :(得分:0)

LinqTo2Db支持Window-Functions LagLead

from p in db.Parent
    join c in db.Child on p.ParentID equals c.ParentID 
    select new
    {
        Lag = Sql.Ext
            .Lag(p.Value1, Sql.Nulls.None)
            .Over()
            .PartitionBy(p.Value1, c.ChildID)
            .OrderBy(p.Value1)
            .ThenBy(c.ChildID)
            .ThenBy(c.ParentID)
            .ToValue(),

        Lead = Sql.Ext
            .Lead(p.Value1, Sql.Nulls.None)
            .Over()
            .PartitionBy(p.Value1, c.ChildID)
            .OrderByDesc(p.Value1)
            .ThenBy(c.ChildID)
            .ThenByDesc(c.ParentID)
            .ToValue(),
    }

在我的情况下,Sql.Nulls.IgnoreSql.Nulls.RespectSQL Server不兼容