C#实习生 2022-03-07 13:45 采纳率: 60%
浏览 53
已结题

SQLserver AVG函数求1到3月的各项平均值

我写了一部分可以求1到3月的总和,求平均值时数据不对
sql语句如下
select
SUM(case when year(D.RQ)=2021 and month(D.RQ)=1 then D.DYM else 0 end) DYM1,
SUM(case when year(D.RQ)=2021 and month(D.RQ)=1 then D.RY else 0 end) RY1,
SUM(case when year(D.RQ)=2021 and month(D.RQ)=2 then D.DYM else 0 end) DYM2,
SUM(case when year(D.RQ)=2021 and month(D.RQ)=2 then D.RY else 0 end) RY2,
SUM(case when year(D.RQ)=2021 and month(D.RQ)=2 then D.RYOU else 0 end) RYOU2,
SUM(case when year(D.RQ)=2021 and month(D.RQ)=3 then D.DYM else 0 end) DYM3,
SUM(case when year(D.RQ)=2021 and month(D.RQ)=3 then D.RY else 0 end) RY3,
from DXTJ A left join GLY_JBXXB B on A.GLY=B.ID left join DEPT_JBXXB C on A.SGDW=C.DEPEID left join CSJING_SCSJB D on A.JH=D.JH
where JB='油井'
数据库格式如下

img

  • 写回答

2条回答 默认 最新

  • DarkAthena ORACLE应用及数据库设计方案咨询师 2022-03-08 01:51
    关注

    你把你的else 0都删掉试试。

    select
    avg(case when year(D.RQ)=2021 and month(D.RQ)=1 then D.DYM  end) DYM1,
    avg(case when year(D.RQ)=2021 and month(D.RQ)=1 then D.RY  end) RY1,
    avg(case when year(D.RQ)=2021 and month(D.RQ)=2 then D.DYM  end) DYM2,
    avg(case when year(D.RQ)=2021 and month(D.RQ)=2 then D.RY  end) RY2,
    avg(case when year(D.RQ)=2021 and month(D.RQ)=2 then D.RYOU  end) RYOU2,
    avg(case when year(D.RQ)=2021 and month(D.RQ)=3 then D.DYM  end) DYM3,
    avg(case when year(D.RQ)=2021 and month(D.RQ)=3 then D.RY  end) RY3,
    from DXTJ A left join GLY_JBXXB B on A.GLY=B.ID left join DEPT_JBXXB C on A.SGDW=C.DEPEID left join CSJING_SCSJB D on A.JH=D.JH
    where JB='油井'
    

    avg不对的原因是,它的算法是求和再除以非空的行数,你这行数没有发生变化,不是指定月份的数据你给了个0,它当然数据会偏小了

    另外,你确定不在后面加个where条件限定下查询数据的范围么?你这样查,整个表的数据都扫到了

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

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 3月8日
  • 已采纳回答 3月8日
  • 创建了问题 3月7日

悬赏问题

  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟