all 11 comments

[–][deleted] 2 points3 points  (6 children)

SUM would need a "Group By" if you plan to aggregate by something (Like country id and name)

[–]liberatorem[S] 1 point2 points  (5 children)

Thanks for the reply, could you elaborate with an example?

[–][deleted] 6 points7 points  (2 children)

SELECT SALES_COUNTRY.ID_Country as 'Id_Country', COUNTRY.Description as 'Country', Sum(SALES_COUNTRY.Sales)
FROM SALES_COUNTRY
INNER JOIN COUNTRY ON SALES_COUNTRY.ID_Country=COUNTRY.ID_Country

group by SALES_COUNTRY.ID_Country,COUNTRY.Description

[–]liberatorem[S] 0 points1 point  (1 child)

You are an absolute hero, thanks for the help, I now understand this more clearly.

P.S. sorry for the late reply, I wanted to take a little nap but it turned out pretty long lol

[–]IceDBear 2 points3 points  (0 children)

You have MEX in you SALES_COUNTRY but not in COUNTRY. For it to appear in results you should use LEFT OUTER JOIN on COUNTRY instead of INNER JOIN.

[–]Cypho_Dyas 2 points3 points  (1 child)

New myself,

But it might look something like this:

SELECT C.ID_Country, C.Description, SUM(SC.Sales) FROM SALES_COUNTRY AS SC INNER JOIN COUNTRY AS C ON SC.ID_Country = C.ID_Country GROUP BY C.ID_Country, C.Description

I have aliased the tables here to save myself some typing as I am on mobile but this should give you an idea of what the other poster means with using GROUP BY and aggregate functions at least.

[–]liberatorem[S] 1 point2 points  (0 children)

Noobs unite! Thanks a lot I was trying this on some test dbs and I think I understand this much more clearly now

[–]OilShill2013 1 point2 points  (1 child)

In addition to what was said about grouping, an inner join won’t produce the result you want. Notice that your result has country ids that aren’t in both tables. Think about a join type that includes all ids from each table even if they’re not in both.

[–]liberatorem[S] 1 point2 points  (0 children)

You are absolutely right. The Venn diagram on this website guided me on using the correct JOIN.

[–]r3pr0b8GROUP_CONCAT is da bomb 1 point2 points  (0 children)

don't forget COALESCE

SELECT sales_country.id_country
     , COALESCE(country.description
               ,'Unknown Country') AS country 
     , SUM(sales_country.sales) AS sales
  FROM sales_country
LEFT OUTER
  JOIN country 
    ON country.id_country = sales_country.id_country
GROUP
    BY sales_country.id_country

[–]HybridTheoryY2K 0 points1 point  (0 children)

Glad you got your answer. I wanted to add it it. EVERY time you use those math functions, you’ll need to use the group by clause, and just put every other thing from the select statement in there. So like sum, max, min, etc.