【问题标题】:Select distinct value of a view with repeated values in sql server在sql server中选择具有重复值的视图的不同值
【发布时间】:2024-05-22 23:00:02
【问题描述】:

我对这个表格结果有一个看法:

id   date         text     name     othertext
--- |-------------|-------|--------|---------
14  | 2013/02/01  | text1 | john   | 399 
14  | 2013/02/02  | text2 | john   | 244
14  | 2013/02/03  | text3 | john   | 555
14  | 2013/02/04  | text4 | john   | 300
13  | 2013/02/05  | text5 | juliet | 200
12  | 2013/02/06  | text6 | borat  | 500
12  | 2013/02/07  | text7 | borat  | 600
10  | 2013/02/08  | text8 | Adam   | 700
10  | 2013/02/09  | text9 | Adam   | 700

它就像一个评论系统。每个用户可以在不同的帖子中发表评论(“id”是帖子的 id)。 我想获得最后评论的帖子列表,按日期排序,但我不想获得发表评论的用户的重复姓名。

这是我想要的结果:

id   date          text    name     othertext
--- |-------------|-------|--------|---------
10  | 2013/02/09  | text9 | Adam   | 700 
12  | 2013/02/07  | text2 | borat  | 600
13  | 2013/02/05  | text5 | juliet | 200
14  | 2013/02/04  | text4 | john   | 300

最后:我想知道最后评论但没有重复的帖子的id。

非常感谢!!!!

【问题讨论】:

    标签: sql sql-server group-by distinct


    【解决方案1】:

    有很多方法可以实现您想要的。由于是SQL Server,所以可以使用ROW_NUMBER()等排名功能

    SELECT  id, date, text, name, othertext
    FROM    
            (
                SELECT  id,date,text,name,othertext,
                        ROW_NUMBER() OVER (PARTITION BY ID ORDER BY date DESC) rn
                FROM    tableName
            ) a
    WHERE   rn = 1
    ORDER   BY id
    

    【讨论】:

      【解决方案2】:
      select t.*
      from your_table t
      inner join 
      (
         select id, max(date) as mdate
         from your_table
         group by id
      ) x on x.id = t.id and t.date = x.mdate
      order by t.date desc
      

      【讨论】:

      • 如果您将 x.mdate 更改为 x.m_date,它会完美运行。很好很快的回答,非常感谢!