小编典典

SQL-仅基于某些列的“ DISTINCT”?

sql

我有两个表的数据库。其中一个表包含用户,另一个表包含这些用户的地址。每个用户可能有多个地址(尽管每个地址仅与一个用户相关联。)

我想创建一个搜索,即使每个用户有多个地址,它也只为每个用户返回一个条目。搜索返回的地址并不重要-搜索首先找到的内容就足够了。

这是示例搜索结果:

tst  olix  Chicago  IL  USA
tst  olix  Los Angeles  CA  USA
tst2 olix2 Houston  TX USA

我需要这样的搜索,使其仅返回2行,而不是3行。

有任何想法吗?

SELECT DISTINCT
    Users.Firstname, Users.Surname, Users.UserId, 
    Users.Recommendations, Addresses.City, Addresses.Region,
    Addresses.Country
FROM
    Users INNER JOIN
    Addresses ON FT_TBL.UserId = Addresses.UserId
ORDER BY
    Users.Recommendations

阅读 196

收藏
2021-03-17

共1个答案

小编典典

如果Addresses有一个ID字段:

(已针对SQL-Server更新)

SELECT 
    Users.Firstname,
    Users.Surname,
    Users.UserId, 
    Users.Recommendations,
    Addresses.City,
    Addresses.Region,
    Addresses.Country
FROM
    Users INNER JOIN
    Addresses ON Users.UserId = Addresses.UserId
WHERE Addresses.ID = 
    ( SELECT TOP 1 A2.ID
      FROM Addresses AS A2
      WHERE Users.UserId = A2.UserId
    )
ORDER BY
    Users.Recommendations

使用SQL Server的窗口和排名功能:

SELECT 
    Users.Firstname,
    Users.Surname,
    Users.UserId, 
    Users.Recommendations,
    Addresses.City,
    Addresses.Region,
    Addresses.Country
FROM
    Users INNER JOIN
     ( SELECT *
            , ROW_NUMBER() OVER (PARTITION BY UserID) AS rn
       FROM Addresses
     ) AS Addresses ON Users.UserId = Addresses.UserId
                    AND Addresses.rn = 1
ORDER BY
    Users.Recommendations
2021-03-17