如何根据日期从另一个表取数UPDATE到本表(非精确日期匹配)?

chenyun122 2006-02-17 04:56:36
比如
表A
Date Value
20050205 (null)
20050215 (null)


表B
Date Value
20050201 100
20050210 200

从表B中取数更新到表A的Value,规则是取离表A中日期向后最近的Value.
以上例子更新后的结果应该是:
表A更新后
Date Value
20050205 100 (表B中20050101记录日期向后最近)
20050215 200 (表B中20050105记录日期向后最近)

求SQL语句.要求不用到函数和游标.
...全文
206 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
chenyun122 2006-02-24
  • 打赏
  • 举报
回复
经测试,wgsasd311(自强不息) 的答案是正确的.
是我在别名上的处理不当引起了以上发贴中的错误.
感谢wgsasd311(自强不息)!
遗憾的是贴子已结,无法调分.希望下次能再次得到你的帮助.
wgsasd311 2006-02-20
  • 打赏
  • 举报
回复
楼主你测试错了,我的语句没能错误,你测试不对,我取的是别名(A,B)如果你的两个表正好是A ,B ,那别名要相应该下,否则后面的 not exists(select 1 from b where [date]<a.[date] and [date]>b.[date] )语句中[date]>b.[date]根本就是不成立的,因为系统区分不出后面的
b.[date]和前面的[data]是两个表,原意是取前面表.楼主测试请稍改就可以测出效果了......
create table A
(
date varchar(10),
value int
)

create table B
(
date varchar(10),
value int
)

insert A select '20050205', null
insert A select '20050215', null


insert B select '20050202', 200 --注意这里把20050202写在20050201之前
insert B select '20050201', 100 --并且两个日期都是小于A表所有日期


update a set value=t2.value from a , b t2
where t2.[date]<a.[date] and not exists(select 1 from b where [date]<a.[date] and [date]>t2.[date] )


select * from A

drop table A
drop table B
chenyun122 2006-02-18
  • 打赏
  • 举报
回复
感谢两位的作答.
scmail81(琳·风の狼) 的答案非常正确.
wgsasd311(自强不息) 的答案在一般情况下也能得到正确的结果,但not exists(select 1 from tb where [date]<a.[date] and [date]>b.[date] )并不能完全取得"日期向后最近"的效果,只能取得物理位置向后最近的记录.
比如在以下语句:
create table A
(
date varchar(10),
value int
)

create table B
(
date varchar(10),
value int
)

insert A select '20050205', null
insert A select '20050215', null


insert B select '20050202', 200 --注意这里把20050202写在20050201之前
insert B select '20050201', 100 --并且两个日期都是小于A表所有日期


update a set value=b.value from a, b
where a.[date]>b.[date] and not exists(select 1 from b where [date]<a.[date] and [date]>b.[date] )


select * from A

drop table A
drop table B

得到的结果是
Date Value
20050205 100
20050215 100

而正确的结果应该是

Date Value
20050205 200
20050215 200
$扫地僧$ 2006-02-17
  • 打赏
  • 举报
回复
create table A
(
date varchar(10),
value int
)

create table B
(
date varchar(10),
value int
)

insert A select '20050205', null
insert A select '20050215', null


insert B select '20050201', 100
insert B select '20050210', 200


update A set value=(select top 1 value from B where date<=A.date order by date DESC)
wgsasd311 2006-02-17
  • 打赏
  • 举报
回复
update a set value=b.value from ta a,tb b
where a.[date]>b.[date] not exists(select 1 from tb where [date]<a.[date] and [date]>b.[date] )
chenyun122 2006-02-17
  • 打赏
  • 举报
回复
以上写错,修改如下

比如
表A
Date Value
20050205 (null)
20050215 (null)


表B
Date Value
20050201 100
20050210 200

从表B中取数更新到表A的Value,规则是取离表A中日期向后最近的Value.
以上例子更新后的结果应该是:
表A更新后
Date Value
20050205 100 (表B中20050201记录日期向后最近)
20050215 200 (表B中20050210记录日期向后最近)

求SQL语句.要求不用到函数和游标.

22,300

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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