简体   繁体   中英

Joining three columns from three tables and then grouping the distinct values in the first column by the maximum value in the third column

I have joined three tables into one, to receive the following table:

client_name country_name num_customers
Client 1 Albania 1
Client 1 Bosnia 22
Client 1 Croatia 2
Client 1 Germany 2
Client 1 England 1
Client 1 Macedonia 4
Client 1 Montenegro 3
Client 1 Serbia 4502
Client 1 Turkey 1
Client 2 Belgium 921
Client 2 England 3
Client 2 Malta 3
Client 2 Romania 7
Client 2 Sweden 1
Client 3 Latvia 1
Client 3 Lithuania 1848
Client 4 Italy 143
Client 5 Albania 1
Client 5 Algeria 4
Client 5 Armenia 4
Client 5 Austria 3
Client 5 Azerbaijan 1
Client 5 Belgium 5746

My query for joining these three tables looks like this:

SELECT c1.client_name, c2.country_name, count(c3.customer_id) AS num_customers
FROM 
clients c1
LEFT JOIN countries c2 ON c1.fk_country = c2.country_id
LEFT JOIN customers c3 ON c1.fk_customer = c3.customer_id
GROUP BY c1.client_name, c2.country_name;

NOW. I need to expand this query so that my table only includes the country per each client with the maximum number of customers: So the final table should look like this:

client_name country_name num_customers
Client 1 Serbia 4502
Client 2 Belgium 921
Client 3 Lithuania 1848
Client 4 Italy 143
Client 5 Belgium 5746

I tried adding a having clause or cross joining max(num_customers) but could only return one row. Help please?!

You can use window functions:

SELECT client_name, country_name, num_customers
FROM (SELECT c1.client_name, c2.country_name, COUNT(*) AS num_customers,
             ROW_NUMBER() OVER (PARTITION BY c1.client_name ORDER BY COUNT(*) DESC) as seqnum
      FROM clients c1 JOIN
           countries c2
           ON c1.fk_country = c2.country_id JOIN
           customers c3
           ON c1.fk_customer = c3.customer_id
      GROUP BY c1.client_name, c2.country_name
     ) ccc
WHERE seqnum = 1;

Note: I switched the joins to inner joins, under the assumptions that all clients have a country. Perhaps you have clients in Bar Tawil .

Here is a db<>fiddle showing that the syntax works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM