这是我在SQL中使用的查询
select distinct d.npa, n.time_zone, count(n.time_zone) as tz_count
from #duplicates d
inner join psi.npanxx n
on d.npa = n.npa
where n.time_zone is not null and n.time_zone <> '0'
group by --d.npanxx_row_id, d.npa, n.time_zone
order by npa
我得到的结果是这样的
npa time_zone tz_count
208 5 10600
208 4 31300
219 6 7882
219 9 7446
我需要获得最高计数,所以看起来像这样
npa time_zone tz_count
208 5 10600
219 6 7882
如果有任何我可以使用的功能,请告诉我。 提前感谢您的帮助。
答案 0 :(得分:1)
而不是COUNT
,正确的SQL关键字是MAX
select distinct d.npa, n.time_zone, max(n.time_zone) as tz_count
from #duplicates d
inner join psi.npanxx n
on d.npa = n.npa
where n.time_zone is not null and n.time_zone <> '0'
group by --d.npanxx_row_id, d.npa, n.time_zone
order by npa
这是一个小例子。它使用不同的数据集,但使用相同的MAX-Group BY
公式。
答案 1 :(得分:0)
如果我理解正确,您可以使用row_number()
:
select d.npa, d.time_zone, d.tz_count
from (select d.npa, n.time_zone, count(*) as tz_count,
row_number() over (partition by npa order by count(*) desc) as seqnum
from #duplicates d inner join
psi.npanxx n
on d.npa = n.npa
where n.time_zone is not null and n.time_zone <> '0'
group by d.npa, n.time_zone
) d
where seqnum = 1;