写入SQL Server,但实际查询应该在其他数据库上工作。
设置数据:
declare @Fruit table (FruitID int not null,Fruit varchar(10) not null,UnitPrice int not null)
insert into @Fruit(FruitID,Fruit,UnitPrice) values
(1,'Orange',3),
(2,'Apple',2),
(3,'Grape',4)
declare @FruitDetails table (FruitID int not null,Picture varchar(20) not null,Color varchar(10) not null)
insert into @FruitDetails (FruitID,Picture,Color) values
(1,'Orange_o.jpg','Orange'),
(3,'Grape_p.jpg','Purple'),
(3,'Grape_g.jpg','Green'),
(2,'Apple_g.jpg','Green'),
(2,'Apple_r.jpg','Red')
查询:
select
f.Fruit,
f.UnitPrice,
fd.Picture,
fd.Color
from
@Fruit f
inner join
@FruitDetails fd
on
f.FruitID = fd.FruitID
left join
@FruitDetails fd_anti
on
f.FruitID = fd_anti.FruitID and
fd_anti.Picture < fd.Picture --This is the condition for picking a better row
where
fd_anti.FruitID is null --This eliminates rows where a better row was picked
结果:
Fruit UnitPrice Picture Color
---------- ----------- -------------------- ----------
Orange 3 Orange_o.jpg Orange
Grape 4 Grape_g.jpg Green
Apple 2 Apple_g.jpg Green
这不符合您的预期的结果,但是你没有给我们一个很好的从FruitDetail
中挑选“最佳”行的条件的定义。
什么是你加盟吗?你现在查询的是什么样子? –
如何从'FruitDetails'中选择正确的行?你怎么知道葡萄是紫色的而苹果是绿色的? –
wats的逻辑? – manurajhada