我对SQL还是很陌生,所以这可能是一个菜鸟问题:
假设我的查询是:
select [Item], [Answers] from table1
并检索下表:
Item Answers
------------------
Car Expensive
Car Cheap
Car Medium
Boat Expensive
Boat Very Expensive
Boat Ultra Expensive
给定特定的第二张桌子(或字典,我真的不知道该怎么做){便宜:1,中:2,昂贵:3,非常昂贵:4,超昂贵:5}-表示“超昂贵”是最高等级,而“便宜”是最低等级。
在SQL中,对于这种在A列(项目)中有很多重复项的表,如何为A列中的每个唯一值检索B列(答案)中的最高排名值?
在这个例子中,我想得到:
Item Answers
------------------
Car Expensive
Boat Ultra Expensive
在“项目”列中每个重复的值中只有一个,在“答案”中其排名最高的可能值是?
您可以使用相关子查询:
select item, answer
from table1 t
where answer = (
select top 1 answer
from table1 t1
where t1.item = t.item
order by
case answer
when 'Cheap' then 1
when 'Medium' then 2
when 'Expensive' then 3
when 'Very Expensive' then 4
when 'Ultra Expensive' then 5
end desc
)
子查询使用条件子句和过滤answer
具有给定最高排名的的子查询。item
order by
top 1
另一个选择是row_number()
用于过滤:
select item, answer
from (
select
item,
answer,
row_number() over(
partition by item
order by case answer
when 'Cheap' then 1
when 'Medium' then 2
when 'Expensive' then 3
when 'Very Expensive' then 4
when 'Ultra Expensive' then 5
end desc
) rn
from table1
) t
where rn = 1
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句