C# 使用LINQ模拟SQL Server 2012滞后窗口函数
我有一些示例数据如下:(编辑:我没有SQL Server 2012) 下面是我希望用LINQ模拟的SQL查询C# 使用LINQ模拟SQL Server 2012滞后窗口函数,c#,sql,sql-server,linq,C#,Sql,Sql Server,Linq,我有一些示例数据如下:(编辑:我没有SQL Server 2012) 下面是我希望用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 )
;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
在此结果集中,数据的基本格式为
patient ID dischargeDate nextVisitAdmitDate
in_x_days
列中的1表示患者在最后一次出院后30天内再次入院。理想情况下,30
将是用户输入的变量
LINQ中有什么类型的构造可用于执行此操作?LinqToSql没有滞后/超前/行数的分析功能。 您根本无法做到这一点,最简单的方法是将SQL发送到机器,然后在它返回时将结果集映射到您的对象。是.NET的扩展函数库。支持
Lag
和Lead
:
父数据库中p的
在p.ParentID等于c.ParentID的db.Child中加入c
选择新的
{
Lag=Sql.Ext
.Lag(p.Value1,Sql.Nulls.None)
.超过()
.PartitionBy(p.Value1,c.ChildID)
.OrderBy(第1页)
.ThenBy(c.ChildID)
.ThenBy(c.ParentID)
.ToValue(),
Lead=Sql.Ext
.Lead(p.Value1,Sql.Nulls.None)
.超过()
.PartitionBy(p.Value1,c.ChildID)
.OrderByDesc(第1页)
.ThenBy(c.ChildID)
.ThenByDesc(c.ParentID)
.ToValue(),
}
在我的例子中,Sql.Nulls.Ignore
和Sql.Nulls.Respect
不使用Sql Server
是否要在LINQ to Sql查询中使用临时表?无法执行此操作。您的代码中的#base和#temp是同一个表吗?@thepirat000#base和#temp是相同的。实际上,我并没有试图查询临时表,我希望其他人能够快速可视化问题,所以我添加了SQL脚本。
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