一条sql语句,求最大值,最小值,平均值,最新值

saveaswhat 2009-02-16 11:10:51
还是刚才这个帖子,
地址http://topic.csdn.net/u/20090216/10/6f6a1894-1f51-432c-b676-816271ee0cec.html?seed=221566552
表 table
表中列
fgysbm(供应商编码),fsj(时间用来进行排序),fcpbm(产品编码),fdj(单价),fsl(数量)
可能的数据
001 2008-05-02 010101 0.12 126
001 2008-05-03 010101 0.11 212
001 2008-05-04 010101 0.10 526

002 ....................

希望得到的结果
最大单价 最小单价 平均单价1 平均单价2 最新单价 最大数量 最小数量 最新数量
001 010101 0.12 0.10 0.11 0.10 0.10 526 126 526
上面的平均单价1的算法是直接用avg来得出的
还有一种平均单价2应该是 sum(fdj*fsl)/sum(fsl)来得出,


我按照下面的写法写好之后,所有记录的最新单价跟最新数量都是一样的

select fgysbm,fcpbm,
max(fdj) 最大单价,
min(fdj) 最小单价,
avg(fdj) 平均单价1,
sum(fdj*fsl)/sum(fsl)平均单价2,
(select top 1 fdj from table where fgysbm = m.fgysbm and fcpbm = n.fcpbm order by fsj desc) 最新单价,
max(fsl) 最大数量,
min(fsl) 最小数量,
(select top 1 fsl from table where fgysbm = m.fgysbm and fcpbm = n.fcpbm order by fsj desc) 最新数量
from table m
group by fgysbm,fcpbm
...全文
295 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
saveaswhat 2009-02-16
  • 打赏
  • 举报
回复
发贴的时候没反映,以为没有成功,所以点了三次。
saveaswhat 2009-02-16
  • 打赏
  • 举报
回复
是我把表的别名弄错了
orcd 2009-02-16
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 libin_ftsafe 的回复:]
居然发了三个贴?


SQL code
declare @t table(fgysbm varchar(10),fsj datetime,fcpbm varchar(20),fdj numeric(5,2),fsl int)
insert into @t select '001','2008-05-02','010101',0.12,126
insert into @t select '001','2008-05-03','010101',0.11,212
insert into @t select '001','2008-05-04','010101',0.10,526

select fgysbm,fcpbm,
max(fdj) 最大单价,
min(fdj) 最小单价,
av…
[/Quote]
这种写法可以。
-狙击手- 2009-02-16
  • 打赏
  • 举报
回复
M ,n
没有别名n
子陌红尘 2009-02-16
  • 打赏
  • 举报
回复
居然发了三个贴?


declare @t table(fgysbm varchar(10),fsj datetime,fcpbm varchar(20),fdj numeric(5,2),fsl int)
insert into @t select '001','2008-05-02','010101',0.12,126
insert into @t select '001','2008-05-03','010101',0.11,212
insert into @t select '001','2008-05-04','010101',0.10,526

select fgysbm,fcpbm,
max(fdj) 最大单价,
min(fdj) 最小单价,
avg(fdj) 平均单价1,
sum(fdj*fsl)/sum(fsl)平均单价2,
(select top 1 fdj from @t where fgysbm = n.fgysbm and fcpbm = n.fcpbm order by fsj desc) 最新单价,
max(fsl) 最大数量,
min(fsl) 最小数量,
(select top 1 fsl from @t where fgysbm = n.fgysbm and fcpbm = n.fcpbm order by fsj desc) 最新数量
from @t n
group by fgysbm,fcpbm

34,593

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧