如何查询像表结构一样的对?

时间:2014-01-20 12:06:09

标签: sql sql-server

查询前

User   Friend

A      B
A      C
D      A
F      A

查询后

User   Friend

A      B
A      C
A      D
A      F

如何显示结果?我想得到A的所有朋友。

3 个答案:

答案 0 :(得分:2)

有了工会:

select user, friend 
from t
where user = 'A'
union 
select friend, user
from t
where friend = 'A'

注意Union行为distinct是您所期望的(与union all相对)

答案 1 :(得分:0)

试试这个

SELECT  USER AS 'User',
        friend AS 'Friend'
FROM    t
WHERE   USER = 'A'
UNION
SELECT  friend ,
        USER
FROM    t
WHERE   friend = 'A'

答案 2 :(得分:0)

没有UNION

SELECT CASE WHEN [User]='A' THEN [user] ELSE [friend] END as [A], CASE WHEN [User]='A' THEN [friend] ELSE [user] END AS [Friend Of A] WHERE [user]='A' OR [friend]='A'