求SQL语句,可以不用循环而用一条语句实现呢?
Goods_PriceReport 表如下:
IdStuffPrice
4白菜3.2
2番茄5.6
1黄瓜2.3
5辣椒4.5
3芹菜1.2
6土豆9.8
Goods_Order 表如下:
IdStuffPrice
4白菜3.2
2番茄5.6
1黄瓜2.3
5辣椒4.5
3芹菜1.2
6土豆9.8
Goods_Deal 表如下
IdStuffPriceVol
有三个表 Goods_PriceReport 表 Goods_Order表 Goods_Deal 表。
当Goods_Order表中蔬菜价格大于等于Goods_PriceReport中蔬菜价格时,把Goods_Order表中的蔬菜和价格添加到Goods_Deal表,并删除Goods_Order表中的对应内容。
这个操作可以用一条语句解决么??
[解决办法]
要么更新,要么删除,一句话搞不定...
[解决办法]
INSERT INTO Goods_DealSELECT *,Vol=a.Price-b.Price FROM Goods_Order a WHERE EXISTS (SELECT 1 FROM Goods_PriceReport b WHERE a.Price>=b.Price)DELETE Goods_Order WHERE id IN (SELECT id FROM Goods_Deal )
[解决办法]
--> 测试数据:[Goods_PriceReport]if object_id('[Goods_PriceReport]') is not null drop table [Goods_PriceReport]create table [Goods_PriceReport]([Id] int,[Stuff] varchar(4),[Price] numeric(2,1))insert [Goods_PriceReport]select 4,'白菜',3.2 union allselect 2,'番茄',4.9 union allselect 1,'黄瓜',2.3 union allselect 5,'辣椒',5.9union allselect 3,'芹菜',1.2 union allselect 6,'土豆',7.9--> 测试数据:[Goods_Order]if object_id('[Goods_Order]') is not null drop table [Goods_Order]create table [Goods_Order]([Id] int,[Stuff] varchar(4),[Price] numeric(2,1))insert [Goods_Order]select 4,'白菜',3.2 union allselect 2,'番茄',5.6 union allselect 1,'黄瓜',2.3 union allselect 5,'辣椒',4.5 union allselect 3,'芹菜',1.2 union allselect 6,'土豆',9.8--> 测试数据:[Goods_Deal]if object_id('[Goods_Deal]') is not null drop table [Goods_Deal]create table [Goods_Deal]([Id] int,[Stuff] varchar(10),[Price] float,[Vol] varchar(10))--插入:insert [Goods_Deal](Id,[Stuff],Price)select a.*from [Goods_PriceReport] a inner join [Goods_Order] b on a.Id=b.Id and a.[Stuff]=b.[Stuff]where a.Price>=b.Priceselect * from [Goods_Deal]/*Id Stuff Price Vol4 白菜 3.2 NULL1 黄瓜 2.3 NULL5 辣椒 5.9 NULL3 芹菜 1.2 NULL*/--删除:delete from [Goods_Order] where Id in(select Id from(select a.*from [Goods_PriceReport] a inner join [Goods_Order] b on a.Id=b.Id and a.[Stuff]=b.[Stuff]where a.Price>=b.Price )a)select * from [Goods_Order]/*Id Stuff Price2 番茄 5.66 土豆 9.8*/改了你的测试数据,price都是一样的,看不出效果,我改了一下