如何在第一次出现时停止 WHERE?

How to stop WHERE at first occurrence?

期望 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

重要提示:不清楚您所说的 第一次 是什么意思,因为您的示例 table 没有显示可用于对记录进行排序的列。我仍然假设存在这样一个列,并称为 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,否则根本就没有 "first occurrence" 的概念 - 您明天获得的记录顺序可能与今天获得的顺序不同。而是分组和聚合:

SELECT x, MAX(y) as y
FROM table 
GROUP BY x

这产生了最高的出现次数(相当于 "first occurrence when order by descending")

虽然它不适用于多个聚合列;如果您有两列或更多列要检索,请尝试:

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)