如果我们想从表1
中表2 的形式获得结果,那么SQL查询应该是什么?表1:
Type1 | Type2
------|-------
A | Dev
B | User
C | User1
User | Dev
User1 | User
User2 | User1
表2:
X| Y
------|-------
A | Dev
B | User
B | Dev
C | User1
C | User
C | Dev
User | Dev
User1 | User
User1 | Dev
User2 | User1
User2 | User
User2 | Dev
答案 0 :(得分:3)
在此处使用递归CTE尝试以下脚本。
DECLARE @TABLE TABLE
(
Type1 NVARCHAR(10)
,Type2 NVARCHAR(10)
)
INSERT INTO @TABLE
VALUES ('A','Dev'),('B','User'),('C','User1'),('User','Dev'),('User1','User'),('User2','User1')
;WITH CTE
AS
( SELECT Type1,Type2
FROM @TABLE
UNION ALL
SELECT C.Type1, T.Type2
FROM CTE AS C
INNER JOIN @TABLE AS T ON T.Type1 = C.Type2
)
SELECT * FROM CTE
ORDER BY Type1,Type2 DESC
输出
Type1 Type2
A Dev
B User
B Dev
C User1
C User
C Dev
User Dev
User1 User
User1 Dev
User2 User1
User2 User
User2 Dev
答案 1 :(得分:1)
select t1.Type1 as X,
t2.Type2 as Y
from table1 t1
join (select distinct Type2 from table1) t2
on t1.Type2 >= t2.Type2
order by x, y desc
执行为:
SQL>select t1.Type1 as X,
SQL& t2.Type2 as Y
SQL&from table1 t1
SQL&join (select distinct Type2 from table1) t2
SQL& on t1.Type2 >= t2.Type2
SQL&order by x, y desc;
X Y
========== ==========
A Dev
B User
B Dev
C User1
C User
C Dev
User Dev
User1 User
User1 Dev
User2 User1
User2 User
User2 Dev
12 rows found