简体   繁体   English

SQL-选择所有最新的唯一记录

[英]SQL - Selecting all latest unique records

I'm struggling a bit at creating an SQL query to select some records from an Access Database (using Excel VBA). 我在创建SQL查询以从Access数据库(使用Excel VBA)中选择一些记录方面有些挣扎。

A cut of one of the tables (let's call it 'table1') has the following columns: 其中一个表(称为“ table1”)的一部分包含以下几列:

| my_id | your_id | phase |

| 1     | 1       | Open  |

| 2     | 1       | Close |

| 3     | 2       | Open  |

| 4     | 3       | Close |

| 5     | 2       | Close |

| 6     | 3       | Open  |

The field 'my_id' will always be a unique value whereas the 'your_id' field may contain duplicates. 字段“ my_id”将始终是唯一值,而“ your_id”字段可能包含重复项。

What I would like to do is select everything from the table for the most recent record of the 'your_id' where the phase is 'Close'. 我想做的是从表中选择“ your_id”的最新记录,其中阶段为“ Close”。 So that means in the above example table it would select 5, 4 & 2. 因此,这意味着在上面的示例表中它将选择5、4和2。

Hope this makes sense, sorry if not - I'm struggling to articulate what I mean! 希望这是有道理的,如果没有,对不起-我正在努力表达我的意思!

Thanks 谢谢

Although from ur example if u just add where conditin as phase='Close' u will get the records of 5,4 and 2. But I am assuming that there might be scenarios (not in ur example) where more than 1 record can come with status as Close for any given your_id so query should look like this 尽管从ur的示例中,如果您只是添加conditin作为phase ='Close',您将获得5,4和2的记录。但是我假设在某些情况下(而不是在ur的示例中)可以出现1条以上的记录对于任何给定的your_id,其状态均为“关闭”,因此查询应如下所示

 Select * from table1 where my_id in (
   Select Max(My_Id) from table1 where phase='Close' group by your_id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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