找出一个年龄段的平均年龄范围

时间:2016-12-16 00:57:23

标签: mysql sql

我需要在name&表格的表格中找到年龄在2到22岁,15到25岁,10到20岁等10岁以下的事件。 age

我创建了返回平均年龄的SQL:

SELECT age, count(age)
FROM member
GROUP BY age
ORDER BY COUNT(age) DESC
LIMIT 1

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

使用agesage_lower和显示名称age_upper的字段创建另一个表age_range来保存您感兴趣的年龄段,例如' 2至22'

使用WHERE子句加入表,将年龄放在较低和较高范围之间。

SELECT `age_range`, COUNT(`age`) AS age_count 
FROM `member` INNER JOIN `ages`
  ON age BETWEEN age_lower AND age_upper
GROUP BY age_range
ORDER BY COUNT(`age`) DESC, `age_range` ASC

SQL Fiddle

答案 1 :(得分:0)

这可能会解决问题。我添加的唯一内容是保存值1..x的表,其中x是您的桶数。 @T可以很容易地用你的MySQL表名替换。对于每个年龄,结果都是年龄下降的所有可能的集合。然后计算多少相等的集合。

  --IGNORE BUILDING TEST DATA IN SQL SERVER
    DECLARE @T TABLE(member INT,age INT)
    DECLARE @X INT 
    SET @X=1 
    WHILE(@X<=100) BEGIN
        INSERT INTO @T SELECT  @X, CAST(RAND() * 100 AS INT)
        SET @X=@X+1
    END

    DECLARE @MinAge INT=1
    DECLARE @MaxAge INT=100

    --YOUR SET TABLE. TO MAKE LIFE EASY YOU NEED A TABLE OF 1..X 
    DECLARE @SET TABLE (Value INT) 
    DECLARE @SET_COUNT INT =10
    DECLARE @LOOP INT=1
    WHILE(@LOOP<=@SET_COUNT) BEGIN
        INSERT @SET SELECT @LOOP
        SET @LOOP=@LOOP+1
    END

    SELECT
        MinAge,
        MaxAge,
        SetCount=COUNT(CountFlag)
    FROM
    (
        SELECT  
            MinAge=AgeMinusSetCount,
            MaxAge=AgePlusSetCount,
            CountFlag=1
        FROM
        (
            SELECT DISTINCT 
                 ThisAge,
                 AgeMinusSetCount=(AgeMinusSetCount-1) + Value,
                 AgePlusSetCount=CASE WHEN (AgeMinusSetCount-1) + Value + @SET_COUNT > @MaxAge THEN @MaxAge ELSE (AgeMinusSetCount-1) + Value + @SET_COUNT END
            FROM
            (
                SELECT 
                   ThisAge=age,
                   AgeMinusSetCount=CASE WHEN (age - @SET_COUNT) < @MinAge THEN @MinAge ELSE (age) - @SET_COUNT END
                FROM 
                   @T       
            )RANGES    
            LEFT OUTER JOIN (SELECT Value FROM @SET) AS FanLeft ON 1=1
        )AS DETAIL
    )AS Summary
    GROUP BY
        MinAge,
        MaxAge
    ORDER BY
        COUNT(CountFlag) DESC