选择一个表行以连接到另一表的每一行

时间:2019-05-06 15:03:11

标签: sql sql-server tsql

我有两个表,部门和帐户。例如:

部门

+--------+--------+
|Company |DptCode  |
+--------+--------+
|SND     |CD41     |
+--------+--------+
|SND     |CD42     |
+--------+--------+

帐户

+--------+--------+
|Company |AcctCode |
+--------+--------+
|SND     |ACT      |
+--------+--------+
|SND     |BBS      |
+--------+--------+
|SND     |DIP      |
+--------+--------+

我正试图编写一个查询来选择要加入的每个部门,以从“客户”表中获取所有客户代码,就像这样

+--------+--------+
|DptCode |AcctCode|
+--------+--------+
|CD41    |ACT     |
+--------+--------+
|CD41    |BBS     |
+--------+--------+
|CD41    |DIP     |
+--------+--------+
|CD42    |ACT     |
+--------+--------+
|CD42    |BBS     |
+--------+--------+
|CD42    |DIP     |
+--------+--------+

如果我需要对它们进行分组,我很难弄清楚如何对它们进行分组,我无法全神贯注于如何进行此联接。当我运行以下查询时,我得到了很多重复的行。

SELECT  d.Company, d.DptCode, a.AcctCode
FROM Departments d
JOIN Accounts a ON d.Company = a.Company

2 个答案:

答案 0 :(得分:1)

使用加入

;WITH CTE_dept(Company ,DptCode  )
AS
(
SELECT 'SND','CD41' UNION ALL    
SELECT 'SND','CD42'  
),CTe_Accounts(Company ,AcctCode )
AS
(
SELECT 'SND','ACT' UNION ALL     
SELECT 'SND','BBS' UNION ALL      
SELECT 'SND','DIP'      
)
SELECT cd.DptCode,
        ca.AcctCode
FROM CTE_dept cd
INNER JOIN CTe_Accounts ca
    ON  ca.Company = cd.Company

结果

DptCode  AcctCode
-----------------
CD41     ACT
CD41     BBS
CD41     DIP
CD42     ACT
CD42     BBS
CD42     DIP

答案 1 :(得分:0)

我认为您需要CROSS JOIN

SELECT DISTINCT d.DptCode, a.AcctCode
FROM Departments d CROSS JOIN
     Accounts a;