我有两个表,一个是Countries
,其中包含codeCountry
和nameCountry
,第二个表Client
包含privat_code_country.
CodeCountry,例如AUS和nameCountry Austria
我想选择所有拥有最少客户数的国家/地区,换句话说,我必须加入这两个表格,找到所有拥有最少客户数量的国家/地区。
在我查询后,我遇到了“不是单组组功能”的问题。
这是我的疑问:
select codeCountry, min(cnt) as Number_of_clients
from (select s.codeCountry, count(*) as cnt
from countries s join
client t
on s.codeCountry = t.privat_code_country
group by s.codeCountry
) t order by number_of_clients desc, codeCountry asc;
我想收听所有客户数量最少的国家,所以我要求的是更正我的查询。 TNX
预期结果是:
CodeCountry Number umber_of_clients
AUS 1
CRO 1
ITA 1
答案 0 :(得分:2)
我并没有完全遵循你的逻辑,你的内部查询已经为每个codeCountry留下了1条记录,为什么你需要选择min(count)?
试试这个:
SELECT * FROM (
select s.codeCountry, count(*) as number_of_clients
from countries s join
client t
on s.codeCountry = t.privat_code_country
group by s.codeCountry) tt
WHERE tt.number_of_clients = (select min(cnt) from(SELECT count(*) as cnt FROM countries s
join client t
on s.codeCountry = t.privat_code_country
group by s.codeCountry))
order by tt.codeCountry asc;
我认为从数据的外观来看,您不必进行连接,只能从客户端表中进行选择:
SELECT * FROM (
SELECT t.codeCountry,count(*) as number_of_clients
FROM client t
GROUP BY t.codeCountry) tt
WHERE tt.number_of_clients = (SELECT MIN(cnt) FROM(SELECT count(*) as cnt FROM client
GROUP BY codeCountry)
)
答案 1 :(得分:2)
你需要一个RANK:
select *
from
(
select s.codeCountry, count(*) as cnt,
rank() over (order by count(*)) as rnk -- rank based on increasing counts
from countries s join
client t
on s.codeCountry = t.privat_code_country
group by s.codeCountry
) dt
where rnk = 1
答案 2 :(得分:2)
如果您想要拥有最少客户数的国家/地区列表:
select x.codeCountry, x.cnt as number_of_clients
from
(
select t.codeCountry, min(t.cnt) over () as min_cnt, t.cnt
from
(
select s.codeCountry, count(*) as cnt
from
countries s
join
client t
on s.codeCountry = t.privat_code_country
group by s.codeCountry
) t
) x
where x.cnt=x.min_cnt
order by codeCountry asc;
答案 3 :(得分:0)
这是我所理解的。
select s.codeCountry, count(*) as cnt
from countries s join client t
on s.codeCountry = t.privat_code_country
group by s.codeCountry
having count(1) > <the value you consider as minimum>
order by s.codeCountry asc;