[期望mytable
,其中x
在多行上可以具有相同的值,但是我们只想捕获第一个(或最后一个)出现。
目标目标:
select *
from my_table
where x IN ('A', 'B', 'C') <<some limit to get the first occurrence>>;
还有一个例子mytable
(第一行是列名):
x y
A 5
A 1
A 3
B 3
B 2
C 8
目标响应(首次出现):
x y
A 5
B 3
C 8
可以使用子查询将其存档吗?
使用distinct on
:
select distinct on (x) x, y
from my_table
where x in ('A', 'B', 'C')
order by x, id
重要:尚不清楚first出现是什么意思,因为您的sampl表没有显示可用于对记录进行排序的列。我仍然假定存在这样的列,并称为id
。
您需要定义顺序的列(可以是递增顺序或日期)
最近发生:
select * from my_table a where not exists( select * from my_table b where a.x = b.x and
a.columnOrder < b.columnOrder)
第一次出现:
select * from my_table a where not exists( select * from my_table b where a.x = b.x and
a.columnOrder > b.columnOrder)
正如其他人指出的那样,除非您指定ORDER BY,否则根本就没有“首次出现”的概念-明天获得的记录顺序可能与今天获得的记录顺序不同。而是分组和聚合:
SELECT x, MAX(y) as y
FROM table
GROUP BY x
这产生最高的出现(等同于“降序排列时的第一次出现”)
虽然不适用于多个汇总列;如果您要检索两个或更多列,请尝试:
SELECT x, y, z
FROM (SELECT x, y, z, ROW_NUMBER() OVER(PARTITION BY x ORDER BY y) r
WHERE r = 1
这将产生每个不同的x,最低的y和相关的z
某些数据库具有您可以使用的ROWID隐藏列
SELECT x, y
FROM my_table P
WHERE ROWID = (SELECT MIN(ROWID) FROM my_table WHERE x = P.x)