2013-07-16 5 views
0

이 SQL 선택을 LINQ로 변환하는 방법을 알아 내려고했지만 아직 설명하지 못했습니다.SQL에서 LINQ로

각 테스트의 각 ID (PersonId)에 대한 최종 테스트 레코드가 매월 1 년마다 표시됩니다. 기본적으로 한 달에 한 사람 씩 마지막 달의 점수를 얻습니다.

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 

하위 쿼리하기 전에 : 사용 하위 쿼리 후

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

최종 결과, 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 
+0

왜 SQL 쿼리 중복 된 항목을 산출한다 ? – StriplingWarrior

+0

그들은 년이 다른 중복을 산출하지 않으며, 주제도 마찬가지다. – Rayshawn

답변

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