获取最新 5 个独特条目

发布于 2024-12-10 07:09:39 字数 463 浏览 0 评论 0原文

我有一个 Access 数据库,我正在使用具有以下结构的 JET 与之交互:

ID  UsersID
1   1
2   2
3   2
4   3
5   1

我想要做的是获取最新的唯一条目。例如:

ID  UsersID
5   1
4   3
3   2

但是,我在混合分组和排序时遇到了麻烦。我尝试过

SELECT DISTINCT [UsersID] FROM [Table] ORDER BY [ID] DESC
SELECT [UsersID] FROM [Table] GROUP BY [UsersID] ORDER BY [ID] DESC

但是,没有运气。注意:如果我从任一查询中省略 ORDER BY [ID] DESC ,它会起作用,但显然排序不符合预期。

I have an Access database that I am interacting with using JET with the following structure:

ID  UsersID
1   1
2   2
3   2
4   3
5   1

What I am trying to do is get the latest unique entries. eg:

ID  UsersID
5   1
4   3
3   2

However, I am having trouble mixing grouping and ordering. I have tried

SELECT DISTINCT [UsersID] FROM [Table] ORDER BY [ID] DESC
SELECT [UsersID] FROM [Table] GROUP BY [UsersID] ORDER BY [ID] DESC

But, no luck. Note: if I leave off the ORDER BY [ID] DESC from either query, it works, but obviously the ordering is not as expected.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

铃予 2024-12-17 07:09:39

您可以通过简单的 GROUP BY 查询获取每个 UserID 的最大 ID 值。

SELECT UserID, Max(ID) AS MaxOfID
FROM [Table]
GROUP BY UserID;

但是我不确定我是否理解 order by 和最新的 5 个要求。如果latest 5 表示上述查询中的5 个最大ID 值,那么请尝试这种方式...

SELECT TOP 5 UserID, Max(ID) AS MaxOfID
FROM [Table]
GROUP BY UserID
ORDER BY 2 DESC;

“Table”不是表的最佳名称。希望您的真实情况使用不同的表名称。 :-)

You can get the largest ID value for each UserID with a simple GROUP BY query.

SELECT UserID, Max(ID) AS MaxOfID
FROM [Table]
GROUP BY UserID;

However I'm not sure I understand the order by and latest 5 requirements. If latest 5 means the 5 largest ID values from the above query, then try it this way ...

SELECT TOP 5 UserID, Max(ID) AS MaxOfID
FROM [Table]
GROUP BY UserID
ORDER BY 2 DESC;

"Table" is not the best name for a table. Hope your real world situation uses a different table name. :-)

吹梦到西洲 2024-12-17 07:09:39
SELECT TOP 5  ID, UserID FROM 
table 
where UserID in (SELECT DISTINCT UserID from table ORDER BY ID DESC)
SELECT TOP 5  ID, UserID FROM 
table 
where UserID in (SELECT DISTINCT UserID from table ORDER BY ID DESC)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文