Asp.Net 复杂Linq系列 一

--需求
--两张表
--档案资料表(doc_File)、档案借阅表(doc_Apply)关系为doc_Apply 的字段dA_ApplyID关联doc_File的字段dF_ID
--现要求得到
--档案资料的可供处理申请的次数  dA_State = 0 
--档案资料可强制收回的次数 c.dA_State = 1 and c.dA_Result = 1 and c.dA_IsBack=0
--档案资料可查看历史记录的次数 d.dA_State = 1 and d.dA_Result = 1 and d.dA_ReadTime < '2014-11-20 16:10:11'



--1.sql 2种方式实现

--方法一

select 
  b.dF_DangAn,b.dF_GWFaWenNum,b.dF_Title,a.dA_ID,
  (select COUNT(*) applynum  from doc_Apply as b where b.dA_State = 0 and b.dA_ApplyID=a.dA_ApplyID) 
  as applynum,
  (select COUNT(*) returnnum from doc_Apply as c where c.dA_State = 1 and c.dA_Result = 1 and c.dA_IsBack=0 and c.dA_ApplyID=a.dA_ApplyID) 
  as returnnum,
  (select COUNT(*) returnnum from doc_Apply as d where d.dA_State = 1 and d.dA_Result = 1 and d.dA_ReadTime < '2014-11-20 16:10:11' and d.dA_ApplyID=a.dA_ApplyID) 
  as reportnum
  from doc_Apply  as a
  right join doc_File as b on a.dA_ApplyID=b.dF_ID
--方法二

select b.*,a.applynum,a.returnnum from 
(
	select b.dF_ID,
	COUNT(case when a.dA_State = 0 then a.dA_ApplyID else null end)applynum,
	COUNT(case when (a.dA_State=1 and a.dA_Result=1 and a.dA_IsBack=0) then a.dA_ApplyID else null end)returnnum,
	COUNT(case when (a.dA_State=1 and a.dA_Result=1 and a.dA_ReadTime < '2014-11-20 16:10:11') then a.dA_ApplyID else null end)reportnum
	  from doc_Apply a right  join doc_File b on a.dA_ApplyID=b.dF_ID
	  group by b.dF_ID) a join doc_Apply b on a.dF_ID=b.dA_ApplyID


--linq的实现方式(使用了)


var list = (from b in db.doc_File
            join a in db.doc_Apply
            on b.dF_ID equals a.dA_ID
            into gr
            from leftjoin in gr.DefaultIfEmpty()
            where b.dF_Type == id
            select new
            {
                applynum = (from c in b.doc_Apply where c.dA_State == 0 select c).Count(),
                returnnum = (from c in b.doc_Apply where c.dA_State == 1 && c.dA_Result == 1 && c.dA_IsBack == 0 select c).Count(),
                reportnum = (from c in b.doc_Apply where c.dA_State == 1 && c.dA_Result == 1 && c.dA_ReadTime < DateTime.Now select c).Count(),
                b.dF_DangAn,
                b.dF_GWFaWenNum,
                b.dF_Title,
                b.dF_ID,
                b.dF_OperType,
                b.dF_GWID,
                dA_ID = leftjoin == null ? -1 : leftjoin.dA_ID,
            });


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值