gpt4 book ai didi

mysql - SQL group by two fields 计算两个字段

转载 作者:行者123 更新时间:2023-11-30 21:59:23 25 4
gpt4 key购买 nike

我有一些像这样的 MySQL 代码:

select 
Country,
if(upper(District) like 'A%', 'A',
if(upper(District) like '%B', 'B','C')) as Field1Type,
count(*) as Salescount
FROM tablename
group by Country, District;

返回的数据如下:

Country District Salescount
---------------------------
France A 10
France B 20
France C 45
Germany A 30
Germany B 5
Germany C 50

我怎样才能像这样获得每个国家/地区的总数? (我知道效率不是很高,但它只是一张小 table 。

Country District Salescount CountryTotal
----------------------------------------
France A 10 75
France B 20 75
France C 45 75
Germany A 30 85
Germany B 5 85
Germany C 50 85

最佳答案

你可以对总数使用内部连接

  select 
a.Country,
if(upper(a.District) like 'A%', 'A',
if(upper(a.District) like '%B', 'B','C')) as Field1Type,
count(a.*) as Salescount,
t.CountryTotal
FROM tablename as a
INNER JOIN (
Select
Country,
count(*) CountryTotal
FROM tablename
group by Country

) on a.Country = t.country
group by a.Country, a.District;

关于mysql - SQL group by two fields 计算两个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43920403/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com