|---------------------|
|DUN|NAME |BIRTHDAY |
--------------------
|A |MELAYU |21/2/2014|
|A |CINA |21/2/2002|
|B |CINA |21/2/2011|
|-------------------- |
我的表名是maklumat。我想用sql查看基于年龄的数据。下面是要查看的示例表。
|---------------------|
|DUN|AGE<3 |AGE 3-6 |
--------------------
|A |1 |1 |
|B |0 |1 |
|-------------------- |
这就是我做过的事情
SELECT jantina,dun, count(tarikh_lahir > 1954-04-07) as 60KEBAWAH, count(1950-04-07>=tarikh_lahir <= 1954-04-07) as 60HINGGA64, count(1945-04-07>=tarikh_lahir <= 1949-04-07) as 65HINGGA69, count(1940-04-07>=tarikh_lahir <= 1944-04-07) as 70HINGGA74,count(1935-04-07>=tarikh_lahir <= 1939-04-07) as 75HINGGA79,count(1930-04-07>=tarikh_lahir <= 1934-04-07) as 80HINGGA85, count(1925-04-07>=tarikh_lahir <= 1929-04-07) as 86HINGGA89, count(1920-04-07>=tarikh_lahir <= 1924-04-07) as 90HINGGA94, count(1915-04-07>=tarikh_lahir <= 1919-04-07) as 95HINGGA99, count(1910-04-07>=tarikh_lahir <= 1914-04-07) as 100HINGGA104,count(tarikh_lahir <1910-04-07) as 60KEBAWAH
FROM maklumat_ahli
WHERE jantina = 'lelaki' AND (
kematian_tarikh IS NULL
AND bayaran_pertama IS NULL
AND bayaran_kedua IS NULL
)
GROUP BY dun
答案 0 :(得分:0)
SELECT M.DUN, COUNT(M.AGE) AS 'AGE<3', COUNT(M1.AGE) AS 'AGE 3-6' FROM MAKLUMAT M
LEFT JOIN MAKLUMAT M1 ON M.DUN = M1.DUN AND M1.AGE BETWEEN 3 AND 6
WHERE M.AGE < 3
GROUP BY M.DUN
答案 1 :(得分:0)
首先计算年龄。这是今年减去出生年份。例外:今年的生日日期尚未到来。在这种情况下,我们必须减去一个。通过这样发现的年龄,我们可以开始计算,我们可以通过为每个匹配添加一个sum函数来做。
select
dun,
sum(age < 3) as age0to2,
sum(age between 3 and 6) as age3to6
from
(
select
dun,
year(now()) - year(birthday) -
case when month(now()) * 100 + day(now()) < month(birthday) * 100 + day(birthday) then
1
else
0
end
as age
from maklumat
)
group by dun;
答案 2 :(得分:0)
这就是你的select语句失败的原因:MySQL知道一个布尔数据类型,对于FALSE为零,对于TRUE为非零。在计算表达式时,结果为0或1(或NULL)。
表达式(tarikh_lahir&gt; 1954-04-07)在所述日期之后的出生日期为1,出生日期之前为0,出生日期为NULL时仅为NULL。计数所有非空值,零和1,即所有给定的日期。这不是你想要的。
您可以使用SUM代替COUNT来对正结果(即1)求和。此外:据我所知,日期应该是字符串,否则它们将被视为数字表达式,即1954-04-07 = 1954减去04减去07。
SELECT
jantina,
dun,
sum(tarikh_lahir > '1954-04-07') as 60KEBAWAH,
sum('1950-04-07' >= tarikh_lahir <= '1954-04-07') as 60HINGGA64,
sum('1945-04-07' >= tarikh_lahir <= '1949-04-07') as 65HINGGA69,
sum('1940-04-07' >= tarikh_lahir <= '1944-04-07') as 70HINGGA74,
sum('1935-04-07' >= tarikh_lahir <= '1939-04-07') as 75HINGGA79,
sum('1930-04-07' >= tarikh_lahir <= '1934-04-07') as 80HINGGA85,
sum('1925-04-07' >= tarikh_lahir <= '1929-04-07') as 86HINGGA89,
sum('1920-04-07' >= tarikh_lahir <= '1924-04-07') as 90HINGGA94,
sum('1915-04-07' >= tarikh_lahir <= '1919-04-07') as 95HINGGA99,
sum('1910-04-07' >= tarikh_lahir <= '1914-04-07') as 100HINGGA104,
sum(tarikh_lahir <'1910-04-07') as 60KEBAWAH
FROM maklumat_ahli
WHERE jantina = 'lelaki'
AND kematian_tarikh IS NULL
AND bayaran_pertama IS NULL
AND bayaran_kedua IS NULL
GROUP BY jantina, dun;
BTW:MySQL中是否允许以数字开头的名字?否则,您必须找到60HINGGA64等的其他名称或使用引号。