我有一个包含"status"整数字段的重复数据集。我想知道是否有办法将MAX()聚合函数设置为将某些值"设置"为较低优先级。
我最终要做的是在这个数据集上运行一个查询,对重复项进行分组,并选择状态值为"max"的不是"6"的,但如果它是该值并且该记录没有重复项,则返回6。
使用MAX是实现这一目标的最佳方式吗?还是有更好的方法?
select coalesce(max(case when id = 6 then null else id end), max(id))
from (select 6 id union all select 2) a
我同意民主党的改进建议,谢谢@Dems
select coalesce(max(nullif(id, 6)), max(id))
from (select 6 id union all select 2) a
如果"id"从不为空,则可以将max(id)替换为6
declare @T table
(
Grp int,
Val int
)
insert into @T values
(2, 1),
(2, 2),
(2, 6),
(6, 6),
(7, 2),
(7, 6),
(7, 7)
select Val
from
(
select Val,
row_number() over(partition by Grp
order by case when Val = 6
then 1
else 0
end, Val desc) as rn
from @T
) as T
where T.rn = 1
结果:
Val
-----------
2
6
7
如果您使用的是SQL Server,您可能需要探索秩函数。
http://msdn.microsoft.com/en-us/library/ms176102.aspx
使用分级查找重复项