在 SQL 查询中省略聚合列

发布于 2024-10-16 18:44:39 字数 308 浏览 7 评论 0原文

查询中是否可以省略聚合列?举个例子:

SELECT Id, Description, MAX(Created)
FROM Record
GROUP BY Id, Description

如何从结果集中省略 MAX(Created) 列? 此查询正在子查询中使用,因此我可以联接到最新记录并忽略任何较旧的记录。我知道这不会产生很大的差异,但总的来说,我的做法是只带回您需要的数据,在这种情况下,我只想加入最新的记录,并提取描述。我其实并不关心日期是什么。

有什么想法吗?是我太挑剔了吗?

Is it possible to omit an aggregate column in a query? As an example:

SELECT Id, Description, MAX(Created)
FROM Record
GROUP BY Id, Description

How do I omit the MAX(Created) column from my result set? This query is being used in a sub-query so I can join to the most recent record and omit any older records. I know it won't make a large difference, but in general my practice has been to only bring back data you need, and in this case I just want to join to the most recent record, and pull out the description. I don't actually care what the date is.

Any thoughts? Am I being too picky?

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

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

发布评论

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

评论(4

紧拥背影 2024-10-23 18:44:39

如果您只想要最新记录(MAX(已创建))的描述(1 条记录),那么

SELECT TOP 1 Id, Description
FROM Record
ORDER BY CREATED DESC

If you only want the Description (1 record) of the most recent record (MAX(Created)), then

SELECT TOP 1 Id, Description
FROM Record
ORDER BY CREATED DESC
寄居者 2024-10-23 18:44:39
select TOP 1 ID, Description from Record
    group by ID, Description order by MAX(Created) DESC

如果不对列进行分组,则无法使用聚合函数。

就像上面提到的,你甚至可能不需要聚合函数

select TOP 1 ID, Description from Record order by Created DESC
select TOP 1 ID, Description from Record
    group by ID, Description order by MAX(Created) DESC

You cannot use an aggregate function without grouping columns.

And like mentioned above you may not even need an aggregate function

select TOP 1 ID, Description from Record order by Created DESC
笑梦风尘 2024-10-23 18:44:39

除非我误解了这个问题,否则您不能从选择中删除您不需要的列吗?

SELECT Id, Description
FROM Record
ORDER BY Created DESC LIMIT 1

Unless I'm misunderstanding the question, can't you just remove the column you don't want from the select?

SELECT Id, Description
FROM Record
ORDER BY Created DESC LIMIT 1
冰雪之触 2024-10-23 18:44:39
SELECT DISTINCT Id, Description
FROM Record
SELECT DISTINCT Id, Description
FROM Record
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文