SQL - 如何对重复计数结果求和
SQL - How to sum duplicate count result
我的查询有问题。
我想对员工位置进行分类并按地区统计,这里是我的查询:
SELECT
(CASE
WHEN location = 'India' THEN 'Asia'
WHEN location = 'Italy' THEN 'Europe'
WHEN location = 'Singapore' THEN 'Asia'
WHEN location = 'Australia' THEN 'Australia'
ELSE NULL
END) AS Region,
COUNT(location) AS Total_person
FROM
Location_tbl
GROUP BY
location
结果是这样的:
- 亚洲 = 1
- 欧洲 = 1
- 亚洲 = 1
- 澳大利亚 = 1
我想要的结果是这样的:
- 亚洲 = 2
- 欧洲 = 1
- 澳大利亚 = 1
你们能帮我解决一下我的查询,这样我就能得到我想要的结果吗?
您需要在group by
-
中添加自定义组
select
CASE WHEN location in( 'India','Singapore') THEN 'Asia' WHEN location = 'Italy' THEN 'Europe' WHEN location = 'Australia' THEN 'Australia' END as Region,
count(location) as Total_person from Location_tbl
group by CASE WHEN location in( 'India','Singapore') THEN 'Asia' WHEN location = 'Italy' THEN 'Europe' WHEN location = 'Australia' THEN 'Australia' END
select
Region,
count(Region)
from
(select (CASE WHEN location = 'India' THEN 'Asia' WHEN location = 'Italy' THEN 'Europe' WHEN location = 'Singapore' THEN 'Asia' WHEN location = 'Australia' THEN 'Australia' ELSE null END) as Region
from Location_tbl) tab
group by
tab.Region
SELECT
location,
CASE
WHEN location = 'India' or 'Singapore' THEN 'Asia'
WHEN location = 'Italy' THEN 'Europe'
WHEN location = 'Australia' THEN 'Australia'
ELSE NULL
END AS Region
FROM
Location_tbl
GROUP BY
location
ORDER BY
SUM(location);
我的查询有问题。
我想对员工位置进行分类并按地区统计,这里是我的查询:
SELECT
(CASE
WHEN location = 'India' THEN 'Asia'
WHEN location = 'Italy' THEN 'Europe'
WHEN location = 'Singapore' THEN 'Asia'
WHEN location = 'Australia' THEN 'Australia'
ELSE NULL
END) AS Region,
COUNT(location) AS Total_person
FROM
Location_tbl
GROUP BY
location
结果是这样的:
- 亚洲 = 1
- 欧洲 = 1
- 亚洲 = 1
- 澳大利亚 = 1
我想要的结果是这样的:
- 亚洲 = 2
- 欧洲 = 1
- 澳大利亚 = 1
你们能帮我解决一下我的查询,这样我就能得到我想要的结果吗?
您需要在group by
-
select
CASE WHEN location in( 'India','Singapore') THEN 'Asia' WHEN location = 'Italy' THEN 'Europe' WHEN location = 'Australia' THEN 'Australia' END as Region,
count(location) as Total_person from Location_tbl
group by CASE WHEN location in( 'India','Singapore') THEN 'Asia' WHEN location = 'Italy' THEN 'Europe' WHEN location = 'Australia' THEN 'Australia' END
select
Region,
count(Region)
from
(select (CASE WHEN location = 'India' THEN 'Asia' WHEN location = 'Italy' THEN 'Europe' WHEN location = 'Singapore' THEN 'Asia' WHEN location = 'Australia' THEN 'Australia' ELSE null END) as Region
from Location_tbl) tab
group by
tab.Region
SELECT
location,
CASE
WHEN location = 'India' or 'Singapore' THEN 'Asia'
WHEN location = 'Italy' THEN 'Europe'
WHEN location = 'Australia' THEN 'Australia'
ELSE NULL
END AS Region
FROM
Location_tbl
GROUP BY
location
ORDER BY
SUM(location);