【问题标题】:how to find distinct record using Join in SQL server?如何在 SQL Server 中使用 Join 查找不同的记录?
【发布时间】:2014-06-05 07:59:18
【问题描述】:

我必须表一个是用户,第二个是图像。同一 Uid 的图像表中有很多行。如何根据 Uid 找到不同的记录。

User 
ID , int
Date Date

Image 
ImageID int
ImageStatus int
Uid  int  (reference from  User Table)
ImagePath varchar(50)

我正在使用以下查询,但它为 UId 提供了不止一行

select I.Uid, I.ImagePath, I.status from user u inner join Image I on u.Uid=I.Uid  order by u.Date desc

【问题讨论】:

  • 您能否提供数据以及您希望得到的结果。

标签: sql-server join inner-join distinct-values


【解决方案1】:

尝试使用Row_number()Partition

;with cte as
(
select I.Uid, I.ImagePath,rn=row_number()over(partition by I.Uid order by u.Date desc), I.status from user u inner join Image I on u.Uid=I.Uid
)

select * from cte where rn=1

【讨论】:

    【解决方案2】:

    您不需要进行连接,而是可以在图像表中找到不同的 UID。

    select distinct I.Uid from Image I;
    

    或者,如果您想清楚地列出特定列:

    select distinct I.Uid, I.ImagePath, I.status from Image I order by u.Date desc;
    

    【讨论】:

    • @kapildevsharma :试试下面的一个!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-19
    • 1970-01-01
    • 2013-05-12
    • 2019-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多