我一直在尝试根据不同月份的年龄差异生成报告,目前我知道的解决方案是分别为每个月和每个年龄差异分别进行sql查询,这样可以为每个月创建4个不同的sql查询。请告诉我是否可以为每个月创建一个SQL查询,如
如果我想为年龄差异超过40,在50-60之间,在60-70和80以上之间生成JAN的报告
我如何将它放在一个SQL查询中并从中获得四个不同的结果
像(仅限一个想法)
Select count(Above 40),count(In Between 50 - 60),count (In B/W 60-70), count(above 80) from users
答案 0 :(得分:4)
我将IF()和SUM()一起使用如下:
SELECT SUM(IF(age >= 40,1,0)) AS older40,
SUM(IF(age >= 50 and age <= 60,1,0)) AS between50and60
SUM(IF(age >= 60 and age <= 70,1,0)) AS between60and70
SUM(IF(age >= 80,1,0)) AS over80
FROM TABLE
请参阅IF(expr1,expr2,expr3)的MySQL解释,但基本上expr1是条件,expr2是条件为真时的值,expr3是else。使用1&amp; 0为这些允许SUM()计算记录。
答案 1 :(得分:0)
尝试类似
的内容Select Range,Count(*) From
(Select
Case
When (Age >= 40 and Age < 50) Then 'Above40'
When (Age >= 50 and Age < 60) Then 'Between 50 - 60'
When (Age >= 60 and Age < 70) Then 'In B/W 60-70'
When (Age > 80) Then 'Above 80'
else 'Not Counted'
end as Range
From Users) as Ranges
Group By Range
猜测看守,因为你似乎有很多空隙和重叠。
答案 2 :(得分:0)
select *
from (
(select COUNT(Age) as `c1`, '40-50' AS 'freq' from `Users` WHERE Age BETWEEN 40 AND 50)
UNION ALL
(select COUNT(Age) as `c2`, '50-60' AS 'freq' from `Users` WHERE Age BETWEEN 50 AND 60)
UNION ALL
(select COUNT(Age) as `c2`, '60-70' AS 'freq' from `Users` WHERE Age BETWEEN 60 AND 70)
) as aliasquery ;