SQL group by后根据多个条件获取单行
SQL get single row based on multiple condition after group by
需要帮助创建以下案例的查询:
假设我有一个 Table 包含以下记录
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
然后,如果同一日期和时间有多个名称,则根据以下逻辑强制select只记录一个,并在满足以下任一条件时停止。
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
这适用于您的情况,但您需要注意所有值都包含在内,并且 none "contain" 另一个值。
需要帮助创建以下案例的查询:
假设我有一个 Table 包含以下记录
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
然后,如果同一日期和时间有多个名称,则根据以下逻辑强制select只记录一个,并在满足以下任一条件时停止。
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
这适用于您的情况,但您需要注意所有值都包含在内,并且 none "contain" 另一个值。