我有一些像这样的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
我怎样才能获得每个国家的总数,像这样? (我知道这不是很有效但它只是一张小桌子。
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
答案 0 :(得分:0)
你可以使用内部联接和总数
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;