2015-01-06 65 views
1

我使用SQL Server 2008 R2SQL如何獲得x列的名稱相同,但不是在y列

我有一個這樣的表CarLettre

Exp  Desti  Ville   Date 
--------------------------------------------------- 
MDPR GGE LAM  BAYEUX  01/01/2014 12:14 
MDPR GGE azM  RETEDD  01/01/2014 12:14 
MDPR GGE AUT  BOGER   02/01/2014 12:13 
DAC  LAM GGE  BAYEUX  01/01/2014 12:15 
DAC  GGE erT  HUIDFD  02/01/2014 12:13 
DAC  AUT GGE  BOGER   02/01/2014 12:12 

正如你可以看到表我用相同的數據BAYEUX和BOGER獲得了相同的列ville。

我如何獲得與Ville同名的列表,但不是Exp的同名?

當然我能得到這樣的:

SELECT Ville, Date FROM Carlettre where Exp = 'MDPR' 
intersect 
SELECT Ville, Date FROM Carlettre where Exp = 'DAC' 

,但是當我這樣做,我無法將列表

上獲得精通和Desti列,我想是這樣的:

Exp  Desti  Ville   Date 
    MDPR GGE LAM  BAYEUX  01/01/2014 12:14 
    DAC  LAM GGE  BAYEUX  01/01/2014 12:15 
    MDPR GGE AUT  BOGER   02/01/2014 12:13 
    DAC  AUT GGE  BOGER   02/01/2014 12:12 
+0

你可以爲數據提供所需的結果。 –

+0

對於Exp = MDPR,是什麼讓GGE LAM更適合GGE azM? –

+0

Exp = Sender和Desti = Destination ...所以MDPR已經發送了一個包到GGE LAM和GGE AzM – user609511

回答

0

您想獲取存在其他匹配記錄的記錄。有幾種方法可以解決這個問題。一個非常簡單的方法是這樣的,你從同一個表中選擇三次:

select * 
from carlettre 
where exp in ('mdpr','dac') 
and ville in (select ville from carlettre where exp = 'mdpr') 
and ville in (select ville from carlettre where exp = 'dac'); 

爲了查詢同一個表,只有兩次,你可以這樣做:

select * 
from carlettre 
where exp in ('mdpr','dac') 
and exists 
(
    select * 
    from carlettre other 
    where other.ville = carlettre.ville 
    and 
    (
    carlettre.exp = 'mdpr' and other.exp = 'dac' 
    or 
    carlettre.exp = 'dac' and other.exp = 'mdpr' 
) 
); 

或者乾脆:

select * 
from carlettre 
where exp in ('mdpr','dac') 
and ville in 
(
    select ville 
    from carlettre 
    where exp in ('mdpr','dac') 
    group by ville 
    having count(distinct exp) = 2 
); 
0

試試這個:

create table CarLettre 
(
    [Exp] varchar(10), 
    Desti varchar(20), 
    Ville varchar(20), 
    [date] datetime 
); 

insert into CarLettre ([Exp], Desti, Ville, [Date]) values 
('MDPR', 'GGE LAM', 'BAYEUX', '01/01/2014 12:14'), 
('MDPR', 'GGE azM', 'RETEDD', '01/01/2014 12:14'), 
('MDPR', 'GGE AUT', 'BOGER', ' 02/01/2014 12:13'), 
('DAC', 'LAM GGE', 'BAYEUX', '01/01/2014 12:15'), 
('DAC', 'GGE erT', 'HUIDFD', '02/01/2014 12:13'), 
('DAC', 'AUT GGE', 'BOGER', '02/01/2014 12:12'); 

with ranked as 
(
    select * 
    , rank() over (partition by ville order by [exp]) [rank] 
    from CarLettre 
) 
select * 
from CarLettre c 
where exists (
    select * 
    from ranked r 
    where r.ville = c.ville 
    and r.[rank] > 1 
) 

結果:

Exp  Desti  Ville Date 
--------------------------------------------------- 
MDPR GGE LAM  BAYEUX 2014-01-01 12:14:00.000 
MDPR GGE AUT  BOGER 2014-02-01 12:13:00.000 
DAC  LAM GGE  BAYEUX 2014-01-01 12:15:00.000 
DAC  AUT GGE  BOGER 2014-02-01 12:12:00.000 

檢查SQLFiddle

相關問題