SQL GROUP BY only in subquery

I have a dataset for the number of fans of different accounts on 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 try to return all fans by brand, defined as the sum of the maximum fans for each brand:

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 what I get:

ERROR: The subquery uses the ungrouped column account from the external query.

But I do not want to group an external request. You can help?

+6
source share
4 answers

Have you tried writing your request this way?

select  brand, sum(mx)
from    (
            select  brand, account, max(fans) mx
            from    account_fans
            group by brand, account
        ) t1
group by brand
+3
source

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;
+4
source

:

 SELECT T1.brand, sum(A.maximum)
 FROM your_table T1   
 JOIN 
 (
   SELECT brand, account, max(fans) maximum
   FROM your_table T2
   GROUP BY brand, account
 ) A ON T2.brand = T1.brand
 GROUP BY brand
0

:

-- temporary table like your data ------------
DECLARE @account_fans TABLE(brand NVARCHAR(10),account NVARCHAR(10),fans INT)
INSERT INTO @account_fans VALUES ('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)
-- temporary table like your data ------------

SELECT * FROM @account_fans -- your table 


SELECT brand, SUM(fans) fans FROM ( 
SELECT brand,account,MAX(fans) fans FROM @account_fans GROUP BY account,brand 
) A GROUP BY brand -- output you require

, .:)

0

Source: https://habr.com/ru/post/1015905/


All Articles