Select first record in a One-to-Many relation using left join

后端 未结 7 1258
予麋鹿
予麋鹿 2020-12-02 16:52

I\'m trying to join two tables using a left-join. And the result set has to include only the first record from the \"right\" joined table.

Lets say I have two tables

7条回答
  •  庸人自扰
    2020-12-02 17:32

    If you are on SQL Server 2005 or later version, you could use ranking to achieve what you want. In particular, ROW_NUMBER() seems to suit your needs nicely:

    WITH B_ranked AS (
      SELECT
        *,
        rnk = ROW_NUMBER() OVER (PARTITION BY code ORDER BY city)
      FROM B
    )
    SELECT
      A.code,
      A.emp_no,
      B.city,
      B.county
    FROM A
      LEFT JOIN B_ranked AS B ON A.code = B.code AND b.rnk = 1
    

    OR

    WITH B_unique_code AS (
      select * from(
         SELECT
          *,
          rnk = ROW_NUMBER() OVER (PARTITION BY code ORDER BY city)
          FROM B
         ) AS s
      where rnk = 1
    )
    SELECT
      A.code,
      A.emp_no,
      B.city,
      B.county
    FROM A
      LEFT JOIN B_unique_code AS B ON A.code = B.code
    

提交回复
热议问题