Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL GROUP BY only in subquery

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?

like image 531
Derek Hill Avatar asked Mar 21 '17 11:03

Derek Hill


People also ask

Can you have a group by in a subquery?

You can use group by in a subquery, but your syntax is off.

Can we use group by and ORDER BY in subquery?

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.

Can we use group by in SELECT?

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.

Can a subquery be multi valued?

A multi-value subquery retrieves more than one value and has two forms of syntax, as shown below. SELECT ...


2 Answers

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
like image 85
Stefano Zanini Avatar answered Nov 15 '22 04:11

Stefano Zanini


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;
like image 43
Gordon Linoff Avatar answered Nov 15 '22 05:11

Gordon Linoff