如何获取SQL Server中的数据组合?

时间:2019-07-19 08:19:31

标签: sql-server

我有以下数据,需要输出

它将使用所有列的组合并返回可能的输出

XPO GL_CODE  
XPO GL_NAME  
PCARD GL_NAME  
PCARD CHART_OF_CODE  

预期答案:

XPO GL_CODE  
XPO GL_NAME  
PCARD CHART_OF_CODE  
XPO GL_CODE  
PCARD GL_NAME  
PCARD CHART_OF_CODE 

1 个答案:

答案 0 :(得分:0)

所有可能性的组合称为交叉联接(也称为笛卡尔联接):

CREATE TABLE #t 
(
    col1 VARCHAR(20),
    col2 VARCHAR(20)
);

INSERT INTO #t (col1, col2) VALUES
('XPO','GL_CODE'),
('XPO','GL_NAME'), 
('PCARD','GL_NAME'),
('PCARD','CHART_OF_CODE');

WITH cte1 AS 
(
    SELECT DISTINCT col1 FROM #t
),
cte2 AS 
(
    SELECT DISTINCT col2 FROM #t
)
SELECT * 
FROM cte1 
CROSS JOIN cte2;