SQL 一条记录的的两个字段值相同与不同的查询

一条记录有四个字段,第1字段的内容与第3个字段的内容是相同的(但顺序不同),但第2个字段与第4个字段的内容有相同的也有不相同的,如下图所示

如“岳恒勇”在xm和xm01字段内容是一样的,但在je和je01的值不一样,这样的记录我想把相应的字段flag置为1,sql命令如何写呢,多谢

create table #tb
(
xm varchar(20),
je int,
xm01 varchar(20),
flag int 
)
go
insert #tb
select '岳恒勇',2401,'刘良福',0 union all
select '刘良福',2833,'岳恒勇',1 union all
select '曹庆波',2489,'曹庆波',0 union all
select '崔世全',2407,'崔世全',1
go
select * from #tb
where exists(select 1 from #tb b where #tb.xm=b.xm01 and #tb.je<>b.je)
select * from #tb
/*
xm je xm01 flag
------------------------------------
岳恒勇 2401 刘良福 1
刘良福 2833 岳恒勇 0
*/

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-12-26

楼主如下写即可:

UPDATE TABLE SET FLAG = 1 WHERE XM =XM01 AND je <> je01

追问

你的语句没错,但只适合名字的顺序一样的,对于崔世泉的记录能更新成成1,但岳恒勇的就改不了,你能再想想吗,谢谢

追答

你要改的不就是 XM 和XM01 内容一样但是je 和 je01 不一样的数据吗?

第2个回答  2013-12-26
select * from (select xm,je from table) a , (select xm01,je01 from table) b
where a.xm = b.xm01
and a.je <> b.je01追问

这样只是查询出来,想用把查询出来的记录的flag字段更新成1怎么写呢,谢谢了

追答

表没有自增长的ID,只能按照xm+xm01判断,有ID按ID判断最准
update table
set flag = 1
where xm+xm01 in
(
select xm+xm01 from (select xm,je from table) a , (select xm01,je01 from table) bwhere a.xm = b.xm01and a.je b.je01
)

追问

只更新了最后一条记录(置flag为1)而姓名为“岳恒勇”的第一条记录没改成1

追答

你的表有ID字段吗?没有的话试试:
update tableset flag = 1where xm in(select xm from (select xm,je from table) a , (select xm01,je01 from table) bwhere a.xm = b.xm01and a.je b.je01)

追问

谢谢你了,方便告诉我你的QQ吗,还有些不太明白的地方,想请教一下,多谢

本回答被提问者和网友采纳
相似回答