在第 1 行中仅返回一次列值,为其他行返回 NULL


select col1, col2, col3 from table where *some condition*

在这里,返回的行数是不确定的,但 col2 的值将是相同的。 我只想在第一行显示 col2 值,在其他行中显示为 NULL。

如何在不使查询过于复杂的情况下执行此操作?

您可以使用row_number()

select t.col2, (case when t.seq = 1 then t.col2 end) as col2, t.col3
from (select t.col1, t.col2, t.col3,
row_number() over (partition by t.col2 order by ?) as seq
from t
where . . . 
) t;

您可以使用row_number(),但不需要子查询:

select
col1,
case when row_number() over(partition by col2 order by col1, col3) = 1 then col2 end col2
col3
from mytable t
where ...
order by t.col2, col1, col3

请注意,要使其正常工作(并且您的问题完全有意义(,您确实需要在结果集中使用某种排序规则,以便可以明确地告诉它行是第一个。我假设您想使用其他两列对行进行排序(并且我还相应地对结果集进行了排序(。

另请注意,如果结果集中有多个不同的col2,则此解决方案应该同样有效;结果将被排序,并且仅显示给定col2值的第一次出现。

最新更新