如何在内部查询条件中使用外部查询列

时间:2014-10-03 08:50:03

标签: sql sql-server database

我想在select语句中使用子查询,但我想将列数据传递给子查询,以便它可以过滤正在处理的那一行的数据。我们如何做到这一点,或者甚至可能这样做?

select 
[SRP Code], [Master Code],  [Product Desc], [Pack Desc],[Information],  [Store],

case when ([SRP Code] <> [Master Code])
then
    isnull([38],0) + (select (e.stock/er.unit) as 'Stock' from erp_stock e join  
    erpcustomerlinking er on e.productcode = er.mastercode where 

    er.mastercode = [Master Code] <-- here I want the column

    and weekno = 38     group by e.stock,er.unit)
else
    isnull([38],0)
end as [38],[36],[37],[35],[39],[40],[41],[42],[43],[44],[45],[46],[47],[48],[49],[50]

from [dbo].[F91FE39A-F618-40A8-A6F7-C721A379EE76]

where [SRP Code] = 401794

1 个答案:

答案 0 :(得分:0)

是的,这是可能的。

Create table test(id int, name varchar(20), age int);
create table salary(id int, salary int, testid int);

insert into test values(1,'jitu',12);
insert into test values(2,'kapil',12);                 
insert into test values(3,'ajay',12);
insert into test values(4,'vijay',12);

insert into salary values(1, 200, 1);
insert into salary values(2, 300, 2);
insert into salary values(3, 400, 3);
insert into salary values(4, 500, 4);

select *, (select salary from salary where test.id=testid) as Salary from test

小提琴:http://sqlfiddle.com/#!2/717e9/3/0