select 数字不同则 1 否则 0 的情况

select case when number is distinct then 1 else 0

我想得到预期的输出,当 number 在帐户组中第一次出现时,则显示 1,否则如果再次出现,则显示 null 或 0。其他帐户组的逻辑相同。

我能想到的逻辑是

select *,
case when number happens first time then 1 else null 
over (partition by account order by number) from table. 

account number  expected output
abc     20      1
abc     20      0
abc     30      1
def     20      1
def     30      1
def     30      0

使用延迟

  select *,case when number=lag(number) over(partition by account order by account)
           then 0 else 1 end as val
      from table_name

你几乎成功了!

select account, number
case when Row_Number() OVER (partition by account order by number) = 1 THEN 1 END ExpOut
from table

@PaulX 的答案很接近,但分区不太正确。你可以这样做:

-- CTE for sample data
with your_table (account, num) as (
            select 'abc', 20 from dual
  union all select 'abc', 20 from dual
  union all select 'abc', 30 from dual
  union all select 'def', 20 from dual
  union all select 'def', 30 from dual
  union all select 'def', 30 from dual
)
select account, num,
  case when row_number() over (partition by account, num order by null) = 1
       then 1
       else 0
  end as output
from your_table;

ACCOUNT        NUM     OUTPUT
------- ---------- ----------
abc             20          1
abc             20          0
abc             30          1
def             20          1
def             30          1
def             30          0

(针对合法的列名称进行了调整;希望您实际上没有带引号的标识符...)

如果您想要空值而不是零,则只需省略 else 0 部分。这只是假设 'first' 你的意思是第一个在你的结果集中返回,否则 - 至少对于你显示的列 - 没有明显的选择。如果您实际上有其他列,特别是如果您使用任何其他列来对结果集进行排序,那么您可以在 partition 子句中应用相同的排序以使其保持一致。