学无止境,再请教一个MS MQL的insert语句(100分)

  • 主题发起人 主题发起人 Geminiyc
  • 开始时间 开始时间
G

Geminiyc

Unregistered / Unconfirmed
GUEST, unregistred user!
我的表格如下,4个字段,6条记录(假设)——
Km1 Km2 Num Lx
1 1 0.1 X
2 1 0.2 X
2 2 0.3 X
---------
2 1 0.3 Y
2 3 0.6 Y
3 1 0.7 Y
现准备从Lx=X的3条记录中把Lx=Y没有的(KM1,KM2)新增加进去,并修改为Lx=Y,这样的insert语句该如何写?
(即把第1、3条记录插入到表中,并修改它们的lx为‘Y’)
 
我原来想的是——
insert into test (Km1,km2,num,lx) select Km1,km2,num,'Y' from test as b where (b.km1,b.km2) not in (select km1,km2 from test as c where c.lx='Y')
但MS SQL好像不支持 (b.km1,b.km2) in 结构
 
试试这个,我没有测试,可能不行
select a.km1,a.km2,a.Num,'Y' into test from
(select * from test where Lx='X') a,
(select * from test where Lx='Y') b
where a.km1<>b.km1 and a.km2<>b.km2
 
insert into table (km1,km2,lx)
select km1,km2,'Y' from table
where lx='x' and km1+','+'km2' not in (select km1+','+km2 from table where lx='Y')
注释: not in (select km1+','+km2 from table where lx='Y')
用于判断km1和km2不在lx='y' 的条件中,其中逗号','可以改为其它的字符或者不要,但是km1=11,km2=1 和 km1=1和km=11可能判断不出
 
declare @a table(km1 int,km2 int,num money,lx varchar(2))

insert @a values(1,1,0.1,'X')
insert @a values(2,1,0.2,'X')
insert @a values(2,2,0.3,'X')
insert @a values(2,1,0.3,'Y')
insert @a values(2,3,0.6,'Y')
insert @a values(3,1,0.7,'Y')

--select * from @a

insert @a
select km1,km2,num,'Y' from @a where lx='X'
and (cast(km1 as varchar)+cast(km2 as varchar)) not in (select (cast(km1 as varchar)+cast(km2 as varchar)) from @a where lx='Y')

select * from @a
 
xyz500的方法不错,多谢了
 
后退
顶部