我有一张简单的桌子:
id id_fk default
-- ----- -------
1 1 T
2 1 F
3 2 T
4 3 T
5 3 F
我想为每个id_fk
返回一行。如果默认值为T
,则返回该值。如果它们不是默认值T
,则返回默认值F
。
看起来似乎很简单,但我一直在努力。
select t.*
from mytable t
where t.id = (
select top(1) t1.id
from mytable t1
where t1.id_fk = t.id_fk
oder by t1.default desc, t1.id
)
这将为每个id_fk
产生一条记录:优先级为'T'
为default
的记录,然后为较小的id
。
select a.*
from
(select x.*,
row_number() over(partition by x.id_fk order by x.Default desc) as rownum1
from table x) a
where a.rownum1=1
SELECT id_fk, MAX(default) As default
FROM SimpleTable
GROUP BY id_fk