简体   繁体   English

SQL GROUP BY仅在子查询中

[英]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? 你能帮我吗?

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;

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

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

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. 希望能帮助到你。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM