我需要选择 number
不同的行并且是最古老的date
.
我看到了这篇文章:SQL Select Distinct column and latest date
但它在我的情况下不起作用,因为我需要选择所有列,而不仅仅是子句中使用的 2 列。
所以我得到这个错误:
it is not contained in either an aggregate function or the GROUP BY clause` error.
有没有办法选择所有列,以防有行具有相同的 date
,将较旧的视为具有较低 id
的那个?
示例数据:
id name number date
1 foo 1111 06-11-2022
2 bar 2222 01-12-2022
3 baz 3333 12-30-2022
4 foobar 1111 02-01-2022
这是我尝试过的查询:
SELECT id, name, number, MIN(date) as date
FROM my_table
GROUP BY number
使用 Microsoft SQL
最佳答案
当您使用GROUP BY
聚合函数时,您只能使用SELECT
列表中的聚合列。您可以通过多种方式实现预期输出,这是使用窗口聚合函数的一种方式:
select T.*
from (select *,
row_number() over (partition by number order by [date], id) as sn
from my_table
) T
where sn = 1;
关于sql - 选择所有列,但也可以按不同的列和最旧的日期选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73531475/