0

我试图弄清楚如何将此 SQL 选择转换为 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

子查询之前:

图像前

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

SQL 映像

我有的:

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

2 回答 2

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 };
于 2013-07-16T21:22:29.437 回答
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)
于 2013-07-16T21:22:13.503 回答