SQL GROUP BY仅在子查询中

时间:2017-03-21 11:40:33

标签: sql postgresql postgresql-9.5

我为不同品牌的不同日期的不同帐户的粉丝数量设置了一组数据点:

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

我试图按品牌归还粉丝总数,定义为每个品牌帐户的最大粉丝总和:

Ford: 32
Jeep: 72

我尝试了这样的子查询:

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

问题是我得到了:

  

错误:子查询使用来自外部查询的未分组列帐户。

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

4 个答案:

答案 0 :(得分:4)

您需要两个级别的子查询:

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

答案 1 :(得分:4)

您是否尝试过以这种方式编写查询?

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

答案 2 :(得分:0)

尝试以下查询:

 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

答案 3 :(得分:0)

试试这个:

http://www.example.com/my-page.html

希望它有所帮助。 :)