2013-10-22 121 views
0

你能幫我在linq中產生這個sql查詢嗎?嵌套查詢LINQ到實體

SELECT DATA_MAX_qh.DATA_MAX,DATA_MAX_qh.[QUOT_CODE],[QUOT_VALUE],q.QUOT_DESCR,q.QUOT_DESCR_ALIAS 
      FROM [dbo].[QUOTATION_HISTORY] qh INNER JOIN 
      (SELECT MAX(QUOT_DATA) DATA_MAX, QUOT_CODE 
      FROM [dbo].[QUOTATION_HISTORY] 
      GROUP BY [QUOT_CODE]) DATA_MAX_qh on 
      DATA_MAX_qh.DATA_MAX = qh.QUOT_DATA and DATA_MAX_qh.QUOT_CODE = qh.QUOT_CODE 
      inner join [dbo].[AN_QUOTAZIONE] q on q.QUOT_CODE = qh.QUOT_CODE 

我需要的第一件事是組在表上得到最大的日期和它匹配的值 ,然後使用這個過濾表做一個更全面的選擇

我已經開始與此

var qhmaxdatevalue = from qh in context.QUOTATION_HISTORY 
           where qh.QUOT_DATA < System.DateTime.Now 
           group qh by qh.QUOT_CODE into qhgroupedbycode 
           select new { Quot_Code = qhgroupedbycode.Key, Data_Max = qhgroupedbycode.Max(x => x.QUOT_DATA) }; 

但現在我該怎麼辦? 使用嵌套查詢?

你能幫我嗎?

回答

2

也許是這樣的:

var result= (
     from qh in db.QUOTATION_HISTORY 
     from DATA_MAX_qh in 
      (
       from innerqh in db.QUOTATION_HISTORY 
       group innerqh by innerqh.QUOT_CODE into g 
       select new 
       { 
        DATA_MAX=g.Max(x => x.QUOT_DATA), 
        QUOT_CODE=g.Key 
       } 
      ).Where(a=>a.DATA_MAX == qh.QUOT_DATA && a.QUOT_CODE == qh.QUOT_CODE) 
     join q in db.AN_QUOTAZIONE 
      on qh.QUOT_CODE equals q.QUOT_CODE 
     select new 
     { 
      DATA_MAX_qh.DATA_MAX, 
      DATA_MAX_qh.QUOT_CODE, 
      qh.QUOT_VALUE, 
      q.QUOT_DESCR, 
      q.QUOT_DESCR_ALIAS 
     } 
    ).ToList(); 

其中db是LINQ數據上下文

+1

謝謝阿里昂,如果我需要添加\t左加入[DBO] [AN_QUOTAZIONE_CUSTOM] QC上。 qc。[QUOT_CODE] = q.QUOT_CODE \t \t \t其中qc.QUOT_CODE爲空 – user2743368

2
var query = 
context.QUOTATION_HISTORY 
.GroupBy    
(
    x=>x.QUOT_CODE 
) 
.Select 
(
    x=> 
    new 
    { 
     QUOT_CODE = x.Key, 
     DATA_MAX = x.Max(z=>z.QUOT_DATA) 
    } 
) 
.Join 
(
    context.QUOTATION_HISTORY, 
    x=>new{DATA_MAX,QUOT_CODE}, 
    x=>new{QUOT_DATA,QUOT_CODE}, 
    (DATA_MAX_qh,qh)=>new 
    { 
     DATA_MAX_qh.DATA_MAX, 
     DATA_MAX_qh.QUOT_CODE, 
     qh.QUOT_VALUE 
    } 
) 
.Join 
(
    context.AN_QUOTAZIONE, 
    x=>QUOT_CODE, 
    x=>QUOT_CODE, 
    (qh,q)=>new 
    { 
     qh.DATA_MAX, 
     qh.QUOT_CODE, 
     qh.QUOT_VALUE, 
     q.QUOT_DESCR, 
     q.QUOT_DESCR_ALIAS 
    } 
);