您的第一步是构建一个查询来确定最频繁的位置,这很简单:
select Name, Customer, Location, count(*)
from table1
group by Name, Customer, Location
这不是立即有用的,但可以在 row_number() 中使用该逻辑,它为返回的每一行提供一个唯一的 id。在下面的查询中,我按 count(*) 降序排序,以便最频繁出现的值为 1。
注意 row_number() 只返回 '1' 到一行。
所以,现在我们有
select Name, Customer, Location, row_number() over (partition by Name, Customer order by count(*) desc) freq_name_cust
from table1 tb_
group by Name, Customer, Location
最后一步将所有内容放在一起:
select tab.*, tb_.Location most_freq_location
from table1 tab
inner join
(select Name, Customer, Location, row_number() over (partition by Name, Customer order by count(*) desc) freq_name_cust
from table1
group by Name, Customer, Location) tb_
on tb_.Name = tab.Name
and tb_.Customer = tab.Customer
and freq_name_cust = 1