I have a set of datapoints for the number of fans of different accounts for different days belonging to different brands:
|brand|account|date|fans|
|-----|-------|----|----|
|Ford |ford_uk|... |10 |
|Ford |ford_uk|... |11 |
|Ford |ford_us|... |20 |
|Ford |ford_us|... |21 |
|Jeep |jeep_uk|... |30 |
|Jeep |jeep_uk|... |31 |
|Jeep |jeep_us|... |40 |
|Jeep |jeep_us|... |41 |
I'm trying to return the total fans by brand, defined as the sum of the max fans for each of the brand's accounts:
Ford: 32
Jeep: 72
I tried a subquery like this:
(SELECT sum(account_fans)
FROM
(
SELECT max(fans) AS account_fans
GROUP BY account
) subquery_name
) AS total_fans
The problem is that I get:
ERROR: subquery uses ungrouped column account from outer query.
But I don't want to group the outer query. Can you help?
You can use group by in a subquery, but your syntax is off.
ORDER BY command cannot be used in a Subquery. GROUPBY command can be used to perform same function as ORDER BY command. Use single-row operators with singlerow Subqueries.
You can use a SELECT command with a GROUP BY clause to group all rows that have identical values in a specified column or combination of columns, into a single row. You can also find the aggregate value for each group of column values.
A multi-value subquery retrieves more than one value and has two forms of syntax, as shown below. SELECT ...
Have you tried writing your query this way?
select brand, sum(mx)
from (
select brand, account, max(fans) mx
from account_fans
group by brand, account
) t1
group by brand
You need two levels of subqueries:
select brand, sum(fans)
from (select brand, account, max(fans) as fans
from account_fans af
group by brand, account
) ba
group by brand;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With