作为我从我的问题中得到的答案,这让我因为某种原因而疯狂地申请我的代码,为什么它不起作用。
这是我在表格上的一部分数据。
原始代码:
SELECT AGE_RANGE, COUNT(*) FROM (
SELECT CASE
WHEN YearsOld BETWEEN 0 AND 5 THEN '0-5'
WHEN YearsOld BETWEEN 6 AND 10 THEN '6-10'
WHEN YearsOld BETWEEN 11 AND 15 THEN '11-15'
WHEN YearsOld BETWEEN 16 AND 20 THEN '16-20'
WHEN YearsOld BETWEEN 21 AND 30 THEN '21-30'
WHEN YearsOld BETWEEN 31 AND 40 THEN '31-40'
WHEN YearsOld > 40 THEN '40+'
END AS 'AGE_RANGE'
FROM (
SELECT YEAR(CURDATE())-YEAR(DATE(birthdate)) 'YearsOld'
FROM MyTable
) B
) A
GROUP BY AGE_RANGE
这是结果。
我正在尝试做的是,我正在尝试添加另一列,该列将计算该区域中有多少人,正如您在顶部图片中看到的那样,包括珀斯、西澳大利亚、森伯里,维多利亚等。
第一次尝试解决我的问题
正如您将在下面看到的,我添加了位置,并添加了 COUNT(location) loc 来获取位置的名称并计算表中重复的位置数量。
SELECT AGE_RANGE, COUNT(*), location, COUNT(location) loc FROM (
SELECT CASE
WHEN YearsOld BETWEEN 0 AND 5 THEN '0-5'
WHEN YearsOld BETWEEN 6 AND 10 THEN '6-10'
WHEN YearsOld BETWEEN 11 AND 15 THEN '11-15'
WHEN YearsOld BETWEEN 16 AND 20 THEN '16-20'
WHEN YearsOld BETWEEN 21 AND 30 THEN '21-30'
WHEN YearsOld BETWEEN 31 AND 40 THEN '31-40'
WHEN YearsOld > 40 THEN '40+'
END AS 'AGE_RANGE', 'location'
FROM (
SELECT YEAR(CURDATE())-YEAR(DATE(birthday)) 'YearsOld'
FROM event_participants
) B
) A
FROM event_participants WHERE location <> '' GROUP BY location HAVING loc >= 1 ORDER BY loc DESC LIMIT 5
结果到..
显然,听从上帝的帮助并不好。
我第二次尝试解决这个问题
SELECT AGE_RANGE, COUNT(*), location FROM (
SELECT CASE
WHEN YearsOld BETWEEN 0 AND 5 THEN '0-5'
WHEN YearsOld BETWEEN 6 AND 10 THEN '6-10'
WHEN YearsOld BETWEEN 11 AND 15 THEN '11-15'
WHEN YearsOld BETWEEN 16 AND 20 THEN '16-20'
WHEN YearsOld BETWEEN 21 AND 30 THEN '21-30'
WHEN YearsOld BETWEEN 31 AND 40 THEN '31-40'
WHEN YearsOld > 40 THEN '40+'
END AS 'AGE_RANGE', 'location'
FROM (
SELECT YEAR(CURDATE())-YEAR(DATE(birthday)) 'YearsOld'
FROM event_participants
) B
) A
GROUP BY AGE_RANGE
结果是……
它不显示国家/地区的名称,而仅显示位置。
出色地..
长话短说,代码有什么问题?这东西有什么解决办法吗?
就像,我想要的结果是,
AGE_RANGE COUNT(*) location total number of same location
16-20 4 Name of location #
21-30 45 Name of location #
31-40 79 Name of location #
40+ 102 Name of location #