【问题标题】:How to avoid Group By working on every output?如何避免 Group By 处理每个输出?
【发布时间】:2021-11-30 06:28:19
【问题描述】:

我有一张这样的桌子:

LocationID  CountryName  CustomerAmount
C01        Australia     500
C02        Australia     200  
C03        China         100
C04        China         200
C05        Japan         50
C06        Canada        120

我想查找“每个国家/地区的客户数量”和客户总数。

现在我有以下查询:

select countryName, sum(CustomerAmount)
from test
group by countryName;

我显然得到了这个输出:

 CountryName.  customerAmount
 Australia     700
 China         300 
 Japan         50
 Canada        120

但我想要这样的输出

 CountryName.  customerAmount    totalAmount
 Australia     700               1170
 China         300               1170
 Japan         50                1170
 Canada        120               1170

我的问题是如何将两个相同的 sum(customerAmount) 并排放置,但一个按 countryName 分组,而另一个只是汇总 customerAmount 表中的所有值。

提前谢谢你!!!!我不得不说对不起,因为我的表达可能模棱两可。

【问题讨论】:

    标签: mysql sql group-by


    【解决方案1】:

    一种简单的方法就是使用子查询,例如

    select countryName, sum(CustomerAmount) customerAmount,
      (select Sum(customerAmount) from test) totalAmount
    from test
    group by countryName;
    

    如果你可以使用窗口函数(MySql 8+)你可以这样做

    select countryName, sum(CustomerAmount) customerAmount,  
      sum(Sum(CustomerAmount)) over() totalAmount
    from test
    group by countryName;
    

    注意嵌套的 sum()。

    【讨论】:

    【解决方案2】:
    SELECT countryName, SUM(CustomerAmount), SUM(CustomerAmount) OVER()
    FROM test
    GROUP BY countryName;
    

    我没有对此进行测试,但是使用 over 子句应该可以满足您的要求,如 here 所示。

    【讨论】:

    • 您好,感谢您的帮助!这是完美的:D
    猜你喜欢
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-01
    相关资源
    最近更新 更多