从SQL到LINQ

时间:2013-07-16 20:54:02

标签: sql linq entity-framework-4

我想弄清楚如何将这个SQL select转换为LINQ,但我还没有弄明白。

我每个月每年都会获得每个Id(PersonId)的最后一个测试记录。基本上,每个人每年获得最后一个月的分数。

CREATE TABLE #MyTable 
(
   Id INT,
   Score INT,
   TestName VARCHAR(50),
   TestDate DATETIME
)

INSERT INTO #MyTable

VALUES

(1, 10, 'Math', '2011-12-16 00:00:00.000')

,(1, 25, 'Math', '2011-12-26 00:00:00.000')

,(1, 100, 'Math', '2011-12-06 00:00:00.000')

,(1, 10, 'Reading', '2011-12-16 00:00:00.000')

,(1, 25, 'Reading', '2011-12-26 00:00:00.000')

,(1, 100, 'Reading', '2011-12-06 00:00:00.000')

,(2, 10, 'Math', '2011-12-16 00:00:00.000')

,(2, 25, 'Math', '2011-12-26 00:00:00.000')

,(2, 100, 'Math', '2011-12-06 00:00:00.000')

,(2, 10, 'Reading', '2011-12-16 00:00:00.000')

,(2, 25, 'Reading', '2011-12-26 00:00:00.000')

,(2, 100, 'Reading', '2011-12-06 00:00:00.000')

,(1, 10, 'Math', '2011-12-16 00:00:00.000')

,(1, 25, 'Math', '2012-12-26 00:00:00.000')

,(1, 100, 'Math', '2012-12-06 00:00:00.000')

,(1, 10, 'Reading', '2012-12-16 00:00:00.000')

,(1, 25, 'Reading', '2012-12-26 00:00:00.000')

,(1, 100, 'Reading', '2012-12-06 00:00:00.000')

,(2, 10, 'Math', '2012-12-16 00:00:00.000')

,(2, 25, 'Math', '2012-12-26 00:00:00.000')

,(2, 100, 'Math', '2012-12-06 00:00:00.000')

,(2, 10, 'Reading', '2012-12-16 00:00:00.000')

,(2, 25, 'Reading', '2012-12-26 00:00:00.000')

,(2, 100, 'Reading', '2012-12-06 00:00:00.000')



SELECT DISTINCT
M.Id,M.Score,M.TestName, M.TestDate

FROM 
#MyTable M

WHERE
M.TestDate IN (
SELECT MAX(m.TestDate)
FROM #MyTable m
GROUP BY MONTH(TestDate), YEAR(TestDate)
)

DROP TABLE 
#MyTable

在SubQuery之前:

before image http://i43.tinypic.com/rkyps9.png

使用SubQuery后的最终结果,返回结果8条记录:

SQL image http://i42.tinypic.com/b6rbpx.png

我有什么:

  from a in MyTable
  where   a.TestDate == from b in MyTable
   group b.TestDate.Value.Month,
        a.TestDate.Value.Year 

2 个答案:

答案 0 :(得分:2)

试试这个:

from m in myTable
where myTable
    .GroupBy(x => new { x.TestDate.Month, x.TestDate.Year })
    .Select(grp => grp.Max(x => x.TestDate))
    .Any(x => x == m.TestDate)
select new { m.Id, m.TestScore, m.TestName, m.TestDate };

答案 1 :(得分:1)

var q1= 
    from entry in MyTable
    group entry by new{entry.TestDate.Month, entry.TestDate.Year} into g
    select g.Where(entry => entry.TestDate == g.Max(e => e.TestDate));

请注意,这将为每个月/年组合创建组,这可能实际上更适合您的业务案例。如果你需要它变平,你可以说:

var q2 = from g in q1
         from entry in g
         select entry;

或:

var q2 = q1.SelectMany(g => g)