日期:2014-05-17  浏览次数:20809 次

求1条SQL 语句
表A
数据如下   :

月份       工号   字段1
200701   111     12
200702   111     11
200703   111     11
200701   222     13
200702   222     12
200703   222     12

要求
  替换   月份   为   200702、200703   行     的“字段1”   数据
            若同1个工号   “字段1”   的数据   与   200701行数据不一致时,   替换成   200701   行的字段1   的数据

替换结果     如下

月份       工号   字段1
200701   111     12
200702   111     12
200703   111     12
200701   222     13
200702   222     13
200703   222     13

  200702、200703   没有记录的时   忽略


------解决方案--------------------
Update
T1
Set
字段1 = T2.字段1
From
A T1
Inner Join
A T2
On T1.工号 = T2.工号
Where
(T1.月份 = '200702 ' Or T1.月份 = '200703 ')
And
T2.月份 = '200701 '
------解决方案--------------------
update a set 字段1 = b.字段1
from 表A a , (select 工号,字段1 from 表A where 月份= '200701 ' ) b
where a.工号 = b.工号
------解决方案--------------------
update 表A
set 字段1=(select min(字段1) from 表A a where a.工号=b.工号 and left(a.月份,4)=left(b.月份,4))
from 表A b
------解决方案--------------------
baso1623(baso) ( ) 信誉:94 Blog 2007-04-04 10:29:12 得分: 0


还有别的答案吗
注意 是要 忽略 月份 200701 没有记录的工号人员


-------------
我用的是inner join,所以“月份 200701 没有记录的工号人员”不會被更新。

用關聯的效率比用子查詢的效率更優.
------解决方案--------------------
create table t1 (月份 varchar(10), 工号 int , 字段1 int)
insert t1
select '200701 ', 111 , 12 union all
select '200702 ', 111 , 11 union all
select '200703 ', 111, 11 union all
select '200701 ', 222 , 13 union all
select '200702 ', 222 , 12 union all
select '200703 ', 222 , 12


update a set 字段1 = b.字段1
from t1 a , (select 工号,字段1 from t1 where 月份= '200701 ' ) b
where a.工号 = b.工号
------解决方案--------------------
create table t1 (月份 varchar(10), 工号 int , 字段1 int)
insert t1
select '200701 ', 111 , 12 union all
select '200702 ', 111 , 11 union all
select '200703 ', 111, 11 union all
select '200701 ', 222 , 13 union all
select '200702 ', 222 , 12 union all
select '200703 ', 222 , 12 union all
select '200702 ', 333 , 43 union all
select '200703 ', 333 , 43

update a set 字段1 = b.字段1
from t1 a , (select 工号,字段1 from t1 where 月份= '200701 ' ) b
where a.工号 = b.工号
------解决方案--------------------
呵呵,都是SQLserver里的写法,
------解决方案--------------------
update table T1 set 字段1=(select 字段1 from table T2 where T1.月份=T2.月份 and T1.工号=T2.工号)where T1.月份 != '200701 '
------解决方案--------------------
update table set table.字段1=(select 字段1 from (select distinct 工号,字段1 from table where 月份= '200701 ') b