2014-11-23 47 views
0

我正在通過SQL命令從C#訪問數據庫,並想知道如何讀回整個表,但只能使用每個條目的最新日期。我的表如下: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

這是您的查詢:

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; 
+0

我試過!謝謝你的回答,但我得到了一個錯誤:( Openning:System.Data.OleDb.OleDbException(0x80040E14):FROM子句中的語法錯誤 at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr) at System。 Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams,Object&executeResult)----- Thankyou太快了! – blindman457 2014-11-23 04:52:34

+0

再次看着它,並試圖將其作爲我的SQL命令: SELECT ac。* FROM [A&C] AS ac INNER JOIN (SELECT ID [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 我現在有一個錯誤,告訴我'A&C'找不到...幫助! – blindman457 2014-11-23 06:05:00

+0

@ blindman457 ......我無法幫助。你需要使用您的表格的正確名稱以便任何查詢工作。我建議你先從簡單的查詢開始,以確保連接和名稱正常。 – 2014-11-23 13:12:51