LINQ to SQL top和子查询中的order

时间:2011-11-30 06:49:11

标签: linq subquery sql-order-by

我需要下一个SQL查询:

SELECT [t1].[monthp], [t1].[yearp], [t1].[coeftarif]
FROM [dbo].[sal_hightariff] AS [t0]
INNER JOIN [dbo].[sal_tarifstav] AS [t1] ON ((
    SELECT TOP (1) [t3].[code_no]
    FROM [dbo].[sal_tarifstav] AS [t3]
    WHERE ([t3].[codetnum] = @codetnum) AND ([t3].[yearp] = [t0].[yearp]) AND ([t3].[monthp] = [t0].[monthp])
    ORDER BY [t3].[datestart]
    )) = [t1].[code_no]
WHERE [t0].[yearp] * 12 + [t0].[monthp] >= @value1 AND [t0].[yearp] * 12 + [t0].[monthp] <= value2

所以,我写这段代码:

var coeflist = from high in dbContext.sal_hightariff
               join stav in dbContext.sal_tarifstav on (from tarifstav in dbContext.sal_tarifstav
                                                        where tarifstav.codetnum == vacationcodetnum
                                                            && tarifstav.yearp == high.yearp
                                                            && tarifstav.monthp == high.monthp
                                                        orderby tarifstav.datestart
                                                        select tarifstav.code_no).FirstOrDefault() equals stav.code_no
               where high.yearp * 12 + high.monthp >= minday.Year * 12 + minday.Month
                    && high.yearp * 12 + high.monthp <= vacationdatestart.Year
                        * 12 + vacationdatestart.Month
               select new
               {
                   stav.monthp,
                   stav.yearp,
                   stav.coeftarif
               };

但我的代码生成:

SELECT [t1].[monthp], [t1].[yearp], [t1].[coeftarif]
FROM [dbo].[sal_hightariff] AS [t0]
INNER JOIN [dbo].[sal_tarifstav] AS [t1] ON ((
    SELECT TOP (1) [t3].[code_no]
    FROM (
        SELECT [t2].[code_no], [t2].[codetnum], [t2].[yearp], [t2].[monthp]
        FROM [dbo].[sal_tarifstav] AS [t2]
        ORDER BY [t2].[datestart]
        ) AS [t3]
    WHERE ([t3].[codetnum] = @p0) AND ([t3].[yearp] = [t0].[yearp]) AND ([t3].[monthp] = [t0].[monthp])
    )) = [t1].[code_no]
    WHERE ((((CONVERT(Int,[t0].[yearp])) * @p1) + (CONVERT(Int,[t0].[monthp]))) >= @p2)
        AND ((((CONVERT(Int,[t0].[yearp])) * @p3) + (CONVERT(Int,[t0].[monthp]))) <= @p4)

其中有错误:

  

Msg 1033,Level 15,State 1,Line 13 ORDER BY子句无效   视图,内联函数,派生表,子查询和公用表   表达式,除非还指定了TOP或FOR XML。

因此,如果我在子查询中使用方法FirstorDefault()或Take(1),LINQ会生成SELECT TOP(1)FROM SELECT ...但我需要在子查询中使用TOP(1)来使用ORDER BY语句。

0 个答案:

没有答案