简体   繁体   中英

Microsoft Access SQL to return only records where the last record in a set of grouped records equals something in another column

I'll try to explain my question and the data behind it as best I can.

I have a table in Microsoft Access that is structured as follows.

ID1, ID2, Data1, Data2

ID1 - Is a number field that identifies the item (1,2,3,4 etc...)

ID2 - Is a number field that identifies a change to that item (1,2,3,4 etc...) These are both set a primary key. Both IDs are needed for the record to be unique.

Data1 - A data field containing information regarding the change (name of user who made the change)

Data2 - Same thing, just a data field.

I need to run an SQL query on this data to return all records for a particular item in Data1 where ID1 = let's say 1 and ID2 = the latest record in that set.

ID2 can vary in what the last row could be. So if ID1 is 1 there could be 7 ID2s for that ID1 so 7 would be the row I need to check. Where ID1 is equal to 2, there could be 3 items, so now I need the SQL to check both row 7 for ID1=1 and row 3 for ID1=2 to determine if the Data1 in that row equals a certain name.

From what I've been able to research it seems like I'll need to use grouping to get the ID1s together but where I'm failing to find what I'm looking for is to get the max item out of ID2 for each group of ID1s.

Here is where I am at so far.

SELECT ID1, Max(ID2), Data1, Data2
FROM tbl_History
WHERE Data1 = 'name'
GROUP BY ID1
ORDER BY ID2 DESC

Example data:

ID1  |  ID2  |  Data1  |  Data2
--------------------------------
 1       1      Name1      32
 1       2      Name2      23
 1       3      Name3      63
 1       4      Name2      53
 2       1      Name4      12
 2       2      Name5      16
 2       3      Name2      71

Expected result is that if I look for Name2 from Data1 I will get both rows 1-4 and 2-3. If I look for Name5 or any other name other than 2 in this example I will receive no rows because there are no max ID2s with their name is the Data1 column.

The error being returned is Data2 is not part of an aggregate function. I technically already have Data1 so I could take that out of the data being returned but how can I retrieve Data2 based on my above requirements. Maybe grouping isn't the way I need to go.

I am using VB.NET to access a Microsoft Access database through an OleDb connection.

Any help would be appreciated. Please let me know if any further details are required and I'll be happy to post them.

Use a correlated subquery in the where clause:

select h.*
from tbl_history as h
where h.id2 = (select max(h2.id2)
               from tbl_history as h2
               where h.id1 = h2.id1
              );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM