Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get related columns in group by SQL query

Tags:

sql

postgresql

I have a database with data that relate to countries, simplified it looks something like this:

ID | country_id | country_ISO | var_value
1  | 1          | FR          | 10
2  | 2          | BE          | 15
3  | 3          | NL          | 20
4  | 1          | FR          | 6
5  | 2          | BE          | 8
6  | 2          | BE          | 12

I would like to get the sum of the values of "var_value", but with that I want to have the country_id as well country_ISO.

I can do this:

SELECT
  country_ISO,
  SUM(var_value) AS sum_of_value
FROM
  table_name
GROUP BY
  country_ISO;

This query will give me the sum of var_value and the country ISO, but I also want to get the country_id. How do I subquery/self join to get extra columns that are related (in a unique way) to for example country_ISO?

like image 927
Yorian Avatar asked Mar 05 '23 07:03

Yorian


1 Answers

Since country_iso depends on country_id anyway, just extend the GROUP BY by country_id.

SELECT country_id,
       country_iso,
       sum(var_value) sum_of_value
       FROM table_name
       GROUP BY country_id,
                country_iso;
like image 125
sticky bit Avatar answered Mar 16 '23 08:03

sticky bit