Reputation: 6454
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?
Upvotes: 6
Views: 11789
Reputation: 5916
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
Upvotes: 5
Reputation: 1269873
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;
Upvotes: 4
Reputation: 709
Try this:
-- 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
Hope it helps. :)
Upvotes: 0
Reputation: 4192
Try below query :
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
Upvotes: 0