François M.
François M.

Reputation: 4278

SQL: how to select something using information from another table

I have two SQL tables.

In the first table, each line has (amongst other fields that are irrelevant to the question) a score and a category_id field

The second table (categories) is a table listing all the possible categories to which an element in the first table can belong.

I'd like to do the following SQL request :

SELECT category_name, ( ??? ) AS category_score
FROM categories
ORDER BY category_score DESC

where ??? = the sum of the scores of all the elements in table 1 that belong to the category.

Upvotes: 2

Views: 97

Answers (1)

Mureinik
Mureinik

Reputation: 312289

You could join and group by:

SELECT   category_name, SUM(score) AS category_score
FROM     categories c
JOIN     element e ON c.category_id = e.category_id
GROUP BY category_name 
ORDER BY 2 DESC

Upvotes: 3

Related Questions