从不同的表中获取原始数据

时间:2016-06-17 17:44:27

标签: sql sql-server

我在名称栏中有一个表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

我该怎么办?是否可以使用查询将这些列与它们在表中的列完全相同?

2 个答案:

答案 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分别是SalesmanIdCustomers表的主键。现在,这是查询: -

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