日期:2014-05-18  浏览次数:20551 次

求一条SQL语句,在线等
有表t1:
services portid pol pod
  b2 1 盐田 NULL
  b2 2 香港 NULL
  b2 3 NULL 高雄
  b2 4 NULL 关岛
  c1 1 盐田 NULL
  c1 2 NULL 关岛
  c1 3 NULL 纽约
  m1 1 香港 NULL
  m1 2 NULL 关岛
  ..
  ..
我要查出:从某个pol到某个pod的,而且pol的portid=1的services
例如:我查从pol='盐田'到pod='关岛'时的结果应该为:
services 
b2
c1

查从pol='盐田'到pod='关岛'时的结果应该为:
services
m1

这语句应该怎样写?

------解决方案--------------------
我被绕晕了.
------解决方案--------------------
SQL code
--try
declare @pol varchar(16), @pod varchar(16)
select pol='盐田', pod='关岛'
select services
from t1 t
where pol=@pol and portid=1 
   and exists (select 1 from t1 where services=t.services and pod=@pod)

------解决方案--------------------
SQL code

declare @tb table(services nvarchar(5),  portid int,  pol nvarchar(5),  pod nvarchar(5))
insert into @tb
select  'b2',       1,      '盐田', NULL 
union all select  'b2'  ,     2  ,    '香港', NULL 
union all select    'b2'  ,     3,      NULL, '高雄' 
union all select    'b2' ,      4 ,     NULL, '关岛' 
union all select    'c1' ,      1 ,     '盐田', NULL 
union all select    'c1',       2 ,     NULL, '关岛' 
union all select    'c1' ,      3,      NULL, '纽约' 
union all select    'm1' ,      1,      '香港', NULL 
union all select    'm1' ,      2,     NULL, '关岛' 

declare @pol nvarchar(5),  @pod nvarchar(5)
set @pol='香港'
set @pod='关岛' 

select a.services 
from 
@tb a,@tb b
 where @pol=a.pol and @pod=b.pod and a.portid=1 and a.services=b.services
/*
services
--------
m1
*/

如果是pol= '盐田 '到pod= '关岛 '则将set @pol='香港'改成set @pol= '盐田 '
/*
services
--------
b2
c1
*/

------解决方案--------------------

select 
t1.services
from 
table1 t1
join
table1 t2
t1.services=t.services
where
t1.pol='盐田' and t2.pod='关岛'
group by t1.services
------解决方案--------------------
SQL code
select  
    t1.services 
from  
    table1  t1 
join 
    table1 t2 on t1.services=t.services 
where 
    t1.portid=1 and t1.pol= '盐田 ' and t2.pod= '关岛 ' 
group by t1.services