codedvalue 2018-11-06 08:17 采纳率: 80%
浏览 840
已采纳

怎样用1条sql查询出3个时间的数据

一张表table 拥有主键id,姓名name,时间字段date,成绩achievement;怎样使用一条sql语句查询出本月的,上月的以及去年本月3个时间每个人的成绩
用的是mysql

  • 写回答

5条回答 默认 最新

  • Qshu 2018-11-06 08:40
    关注

    with a as (),

    b as (),

    c as ()

    select 姓名,a.成绩 今年本月,b.成绩 今年上月 ,c.成绩 去年本月 from a,b,c

    本年本月
    substr(sysdate,8,2) year
    substr(sysdate,4,2) month

    今年上月
    substr(sysdate,8,2) year
    substr(sysdate,4,2) month-1

    去年本月
    substr(sysdate,8,2) year-1
    substr(sysdate,4,2) month

    a,b,c查询姓名成绩 where date的年等于年,月等于月

    全部SQL如下:
    with a as (select 姓名 ,成绩 from table where date的年=substr(sysdate,8,2) and date的月=substr(sysdate,4,2)),

    b as (select 姓名 ,成绩 from table where date的年=substr(sysdate,8,2) and date的月=substr(sysdate,4,2)-1),

    c as (select 姓名 ,成绩 from table where date的年=substr(sysdate,8,2)-1 and date的月=substr(sysdate,4,2))

    select 姓名,a.成绩 今年本月,b.成绩 今年上月 ,c.成绩 去年本月 from a,b,c

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?