同一表对比

ahhfql 2013-05-17 11:56:49
select mnth,qty ,sign(s1.qty-(select top 1 qty from sales as s2
where s2.mnth < s1.mnth
order by s2.mnth desc)) as sgn
from sales as s1


s2.mnth < s1.mnth好迷糊
哪位帮我解释一下同一表做比较

分不多
...全文
98 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
中关村网名 2013-05-17
  • 打赏
  • 举报
回复
(select top 1 qty from sales as s2 where s2.mnth < s1.mnth order by s2.mnth desc) 这个表示查询S1离目前记录 最近的一条之前的记录,比如说当S1的是1月31号,qty是500, 那么子查询查出离1月31号最近的之前的记录,再相减,判断正负,以此判断是qty随 mnth的变化增加还是减少了。
發糞塗牆 2013-05-17
  • 打赏
  • 举报
回复
你先单独查询s1表,和s2表,看看他们里面是如何的,然后再关联
bichir 2013-05-17
  • 打赏
  • 举报
回复
没什么好解释的,你可以把括号内看成另一个表,他们在查询的时候是互不影响的。
daiyueqiang2045 2013-05-17
  • 打赏
  • 举报
回复
select mnth,qty ,sign
	(
	s1.qty-
		(   
			select top 1 qty 
			from sales as s2 --就当另外一张表看就好了
		    where s2.mnth < s1.mnth
		    order by s2.mnth desc
		)
	) as sgn
 from sales as s1
daiyueqiang2045 2013-05-17
  • 打赏
  • 举报
回复
lz 你的格式太不清晰了。 select mnth,qty ,sign ( s1.qty- ( select top 1 qty from sales as s2 --就当另外一张表看就好了 where s2.mnth < s1.mnth order by s2.mnth desc ) ) as sgn from sales as s1

27,580

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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