我通过SQL命令从C#访问数据库,并想知道如何读回整个表,但只能查看每个条目的最新日期。我的表格如下:
表:
ID Name Begin Date Job Area Co-worker
--------------------------------------------------
1 1/01/2001 M1 Comp3 John Do
1 1/01/2003 M1 Comp3 Jane Do
1 1/01/2010 C2 Comp3 Jane Do
2 1/01/2010 C2 Comp3 John Do
3 12/01/2003 A6 Comp1 Smith John
3 12/01/2004 M2 Comp3 Smith Jack
等...
我知道该表有多个具有相同ID的条目,在不同的日期有不同的工作/同事。我只想循环遍历每个ID,获取该ID的最新信息。我已经找了好几个小时,似乎找不到任何有用的东西(C#似乎很难使用SQL JOIN命令)。我尝试了几种不同的方式,例如:
cmd = new OleDbCommand("SELECT * FROM [A & C] INNER JOIN(SELECT [ID Name], MAX([Begin Date]) AS MaxDate, Job, [Job Area], Co-Worker FROM [A & C] GROUP BY [ID Name]) [A & C] ON([A & C]", connectionObject);
但似乎没有任何工作可做(我已经尝试了很多方法,并意识到问题必须在我看着这个错误),任何人都可以帮忙吗?
答案 0 :(得分:0)
这是您的查询:
SELECT *
FROM [A & C] INNER JOIN
(SELECT [ID Name], MAX([Begin Date]) AS MaxDate, Job, [Job Area], Co-Worker
FROM [A & C]
GROUP BY [ID Name]
) [A & C]
ON ([A & C];
我想你想要这个:
SELECT ac.*
FROM [A & C] as ac INNER JOIN
(SELECT [ID Name], MAX([Begin Date]) AS MaxDate
FROM [A & C] as ac
GROUP BY [ID Name]
) as ac2
ON ac.[ID Name] = ac2.[ID Name] and ac.[Begin Date] = ac2.MaxDate;