【问题标题】:Find the record which have the greater value in top 2 month查找前 2 个月价值较大的记录
【发布时间】:2020-08-24 02:06:54
【问题描述】:

我想检索年龄组大于 50 的记录并显示前 2 个月。

So, this is my table with 3 column 

Age_group infection Month 
30-39     50        2
40-49     11        1
40-49     18        4
50-59     27        2
60-69     30        4
50-59     5         3
70-79     23        3
50-59     4         1 

The result should return like this: 

Month 
4 
3

正如我们在 age_group 中看到的那样,“3”月有 2 行下降。第 3 个月的总值是 28。另一个较大的月份是第 4 个月

【问题讨论】:

    标签: sql database sqlite


    【解决方案1】:

    您必须 group by month 并在排序并返回前 2 之前对感染进行求和:

    select month, sum(infection) total_infection
    from tablename
    where age_group > '50'
    group by month
    order by total_infection desc
    limit 2
    

    请参阅demo
    结果:

    | Month | total_infection |
    | ----- | --------------- |
    | 4     | 30              |
    | 3     | 28              |
    

    【讨论】:

    • 感谢您的解释。我试图弄清楚。
    【解决方案2】:

    这是你想要的吗?

    select t.*
    from t
    where age_group >= '50'
    order by infection desc
    limit 2;
    

    【讨论】:

    • 我不会想到在WHERE 子句中使用直接字符串比较,但我猜你应该实际使用+1。
    • 使用按感染顺序排序,但您如何知道每月的总感染量。因为在第 3 个月有 2 条记录。限制 2 仅显示前 2 行。
    • 您需要按月订购,然后按感染@FufuAlex。
    【解决方案3】:

    根据要求,您似乎首先要按月 desc 排序,然后按感染计数排序,因此这应该是正确的查询:

    select t.*
    from table1 t
    where age_group >= '50'
    order by month desc, infection desc
    limit 2;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-29
      • 1970-01-01
      • 2022-12-07
      • 1970-01-01
      • 2012-11-30
      • 2016-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多