SQL GROUP BY 仅在子查询中

SQL GROUP BY only in subquery

我有一组属于不同品牌的不同帐户在不同日期的粉丝数的数据点:

|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  |

我正在尝试 return 按品牌划分的粉丝总数,定义为每个品牌帐户的最大粉丝数之和:

Ford: 32
Jeep: 72

我试过这样的子查询:

(SELECT sum(account_fans)
  FROM
  (
    SELECT max(fans) AS account_fans
    GROUP BY account
  ) subquery_name
) AS total_fans

问题是我得到:

ERROR: subquery uses ungrouped column account from outer query.

但我不想对外部查询进行分组。你能帮忙吗?

您需要两级子查询:

select brand, sum(fans)
from (select brand, account, max(fans) as fans
      from account_fans af
      group by brand, account
     ) ba
group by brand;

您试过用这种方式编写查询吗?

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

尝试以下查询:

 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

试试这个:

-- 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

希望对您有所帮助。 :)