我在名称栏中有一个表Customers和一个表Salesman:
Table Customers Salesman Table
--name-- --name--
Peter Charlie
Vlado Clint
Landon Tim
Armand
如果我使用此查询:
select a.name as CustomerName, b.name as SalesmanName from Customers a, Salesman b
然后我明白了:
CustomerName SalesmanName
Peter Charlie
Vlado Charlie
Landon Charlie
Peter Clint
Vlado Clint
Landon Clint
Peter Tim
Vlado Tim
Landon Tim
Peter Armand
Vlado Armand
Landon Armand
但想要得到的是:
CustomerName SalesmanName
Peter Charlie
Vlado Clint
Landon Tim
Armand
我该怎么办?是否可以使用查询将这些列与它们在表中的列完全相同?
答案 0 :(得分:4)
您可以使用ROW_NUMBER()
函数生成一个对加入两者有用的任意行号:
;with cust AS (select name,ROW_NUMBER() OVER(ORDER BY name) AS RN from Customers)
,sales AS (select name,ROW_NUMBER() OVER(ORDER BY name) AS RN from Salesman)
select a.name as CustomerName
, b.name as SalesmanName
from cust a
FULL JOIN sales b
ON a.RN = b.RN
ORDER BY COALESCE(a.RN,b.RN)
答案 1 :(得分:1)
我假设您的表中有主键,然后您可以使用 ROW_NUMBER 和 FULL OUTER JOIN 配对这两列。假设vim:tw=78:ts=2:sw=2:expandtab:ft=help:norl:
和CustomerId
分别是SalesmanId
和Customers
表的主键。现在,这是查询: -
Salesman
这是结果
SELECT
ISNULL(CS.Name, '') AS CustomerName,
ISNULL(SM.Name, '') AS SalesmanName
FROM
(
SELECT
Name,
ROW_NUMBER() OVER (ORDER BY CustomerId) AS RN
FROM Customers
) CS
FULL OUTER JOIN
(
SELECT
Name,
ROW_NUMBER() OVER (ORDER BY SalesmanId) AS RN
FROM Salesman
) SM
ON SM.RN = CS.RN