在同一张表中应用条件

时间:2017-02-16 10:26:21

标签: sql sql-server tsql

Primary    Secondary
-----------------------------------
UST         MUN
Data        NULL
Tele        Data
Sun         Data
RMDS        Data
Data        NULL
Mor         NULL
UST         NULL
Data        Bridge

我想检查" Secondary"的价值。已经在"主要"那应该是"主要"但如果它不在"主要"价值必须来自"中学"仅限列。

我希望输出为:

Primary  Secondary
------  -----------
UST      MUN
Data     Bridge
Tele
Sun
RMDS
Mor
Bridge

3 个答案:

答案 0 :(得分:0)

是的 - 你做到了!

您已经获得了足够的经验来与SQL中的自联接斗争......这是您职业发展生涯中的一个重要里程碑

请 - 使用下面的文章(这真的很棒)来弄清楚如何将辅助字段链接到您自己加入的主要字段......基本上它是:)

链接:https://blog.sqlauthority.com/2010/07/08/sql-server-the-self-join-inner-join-and-outer-join/

答案 1 :(得分:0)

假设在Primary下的Bridge不应出现在OUTPUT中。请在下面找到。

SELECT [primary],ISNULL(MAX([Secondary]),'') as [Secondary]
FROM
(SELECT T1.[primary],T2.[Secondary]
FROM 
(SELECT [primary]
FROM #T) T1
JOIN 
(SELECT [primary],[Secondary]
FROM #T  WHERE [Secondary] NOT IN (SELECT [primary]
FROM #T)) T2
ON T1. [primary] = T2.[primary]
GROUP BY T1.[primary],T2.[Secondary]

UNION 

SELECT ONE,NULL FROM
(SELECT [Primary] AS ONE FROM #T
EXCEPT
SELECT [Secondary] FROM #T) X) M
GROUP BY [Primary]

答案 2 :(得分:0)

解决方案的线索是使用Join

全外连接(连接类型)与您想要的非常接近。

SELECT 
* 
FROM
(select distinct [Primary] from test) t1 
Full outer JOIN
(select distinct Secondary 
from test where Secondary not in (select distinct [Primary] from test)) t2
ON t1.[Primary] = t2.Secondary

<强>结果: -

Primary Secondary
NULL    Bridge
Data    NULL
Mor     NULL
NULL    MUN
RMDS    NULL
Sun     NULL
Tele    NULL
UST     NULL