我想弄清楚如何將這個SQL select轉換爲LINQ,但我還沒有弄清楚它。從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
BEFORE子查詢:使用子查詢後
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
爲什麼您的SQL查詢產生重複條目當您選擇不同的值? – StriplingWarrior
他們不會產生重複的年份是不同的,主題也是如此。 – Rayshawn