Skip to content
Advertisement

SQL add a column with COUNT(*) to my query

I need to add a column with the content of this query :

to this query :

I tried adding a LEFT JOIN like that:

with this line in my WHERE statement :

and this line in my SELECT :

but I get an error :

I don’t understand how I could perform this action properly

Advertisement

Answer

To count something, you need to specify a group where that count applies. So every column that you select (and is not used in an aggregate function, like COUNT or SUM), you need to mention in the GROUP BY clause.

Or to put it the other way around: the non-aggregate columns must apply to all rows that are contained in that particular COUNT.

So between the WHERE and ORDER BY clauses, add a GROUP BY clause:


If, on the other hand, you want a count from a different table, you can add a sub-select:

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement