以下情况需要创建查询的帮助:
假设我有一个包含以下记录的表
Name Date Time Category CategoryKey
John 10/20/2012 10:00 Low 2
Sam 10/20/2012 10:00 High 4
Harry 10/20/2012 10:00 Medium 1
Michael 10/20/2012 10:00 Grey 3
Rob 10/22/2013 11:00 Low 2
Marry 10/23/2014 12:00 Low 2
Richard 10/23/2014 12:00 Grey 3
Jack 10/24/2015 1:30 High 4
然后如果相同日期和时间存在多个名称,则根据以下逻辑强制选择一个记录,并在满足以下任一条件时停止。
If Category is Medium then take name
Else If Category is High then take name
Else If Category is Low then take name
Else If Category is Grey then take name
这样最终结果将是
Name Date Time Category CategoryKey
Harry 10/20/2012 10:00 Medium 1
Rob 10/22/2013 11:00 Low 2
Marry 10/23/2014 12:00 Low 2
Jack 10/24/2015 1:30 High 4
row_number()
:select t.*
from (select t.*,
row_number() over (partition by date, time
order by (case category when 'Medium' then 1 when 'High' then 2 when 'Low' then 3 when 'Grey' then 4 else 5 end)
) as seqnum
from t
) t
where seqnum = 1;
在这里使用字符串函数可能很方便:
row_number() over (partition by date, time order by charindex(category, 'Medium,High,Low,Grey') ) as seqnum
这适用于您的情况,但是您需要稍加注意,要包括所有值,并且不要“包含”另一个值。
select t.*
from mytable t
where t.category = (
select top (1) t1.category
from mytable t1
where t1.date = t.date
order by case category
when 'Medium' then 1
when 'High' then 2
when 'Low' then 3
when 'Grey' then 4
end
)