0

你能帮我在 linq 中生成这个 sql 查询吗?

   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) };

但现在我该如何继续?使用嵌套查询?

你能帮助我吗?

4

2 回答 2

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
    }
);
于 2013-10-22T09:16:02.930 回答
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 数据上下文

于 2013-10-22T09:19:32.097 回答