我有一个表格myTable有列
id, foreignID, isDefault, textValue
值可以是这样的
1, 1, 1, NULL 2, 1, 0, NULL 3, 1, 0, 'ABC' 4, 2, 1, 'DE' 5, 2, 0, 'AB' 6, 3, 1, NULL 6, 3, 0, 'DE'
我想为每个foreignID获取一个textValue,其中textValue不为空。
如果对于foreignID有多个不为空的textValues,并且其中一个具有“isdefault=1),我想选择这个textValues。
有什么想法吗? :)
(所以我想要第3,4和6行)
您可以使用row_number()
获取整个行:
select t.*
from (select t.*, row_number() over (partition by foreignId) as seqnum
from myTable t
where textValue is not null
) t
where seqnum = 1;
或者如果只需要TextValue
,请使用聚合:
select foreignId, max(textValue)
from mytable
where textValue is not null
group by foreignId;
您可以尝试下面的方法-在row_number()中添加一个order by子句
select *
from (select *, row_number() over (partition by foreignId order by isDefault desc) as rn
from tablename
where textValue is not null
) A
where rn= 1