代码之家  ›  专栏  ›  技术社区  ›  Breandán

如何根据其他列数据筛选出相似的行(在某些列上相等)

  •  1
  • Breandán  · 技术社区  · 14 年前

    名字 ,那么 身份证件

    用于:

    | Id | Forename | Surname | SomeDate   |
    ----------------------------------------
    | 1  | Bill     | Power   | 2011-01-01 |
    | 2  | James    | Joyce   | 2011-02-01 |
    | 3  | Peter    | Lennon  | 2011-03-01 |
    | 4  | John     | Sellers | 2011-04-01 |
    | 5  | James    | Joyce   | 2011-05-01 |
    | 6  | Peter    | Lennon  | 2011-03-01 |
    

    结果:

    | Id | Forename | Surname | SomeDate   |
    ----------------------------------------
    | 1  | Bill     | Power   | 2011-01-01 |
    | 4  | John     | Sellers | 2011-04-01 |
    | 5  | James    | Joyce   | 2011-05-01 |
    | 6  | Peter    | Lennon  | 2011-03-01 |
    

    1. T-SQL语言
    2. 使用C从数据表#
    2 回复  |  直到 14 年前
        1
  •  2
  •   OMG Ponies    14 年前

    SELECT x.id,
           x.forename,
           x.surname,
           x.somedate
      FROM (SELECT t.id,
                   t.forename,
                   t.surname,
                   t.somedate,
                   ROW_NUMBER() OVER (PARTITION BY t.forename, t.surname 
                                          ORDER BY t.somedate DESC, t.id DESC) AS rank
              FROM TABLE t_ x
    WHERE x.rank = 1
    

    有风险的做法是:

      SELECT MAX(t.id) AS id,
             t.forename,
             t.surname,
             MAX(t.somedate) AS somedate
        FROM TABLE t
    GROUP BY t.forename, t.surname
    
        2
  •  1
  •   Jacob Proffitt    14 年前

    我倾向于对非分组值使用subselect。

    SELECT Forename, Surname, 
        (SELECT TOP 1 Id FROM myTable mt WHERE mt.Forename = m.Forename AND mt.Surname = m.Surname
         ORDER BY m.SomeDate DESC) AS Id
        (SELECT TOP 1 SomeDate FROM myTable mt WHERE mt.Forename = m.Forename AND mt.Surname = m.Surname
         ORDER BY m.SomeDate DESC) AS SomeDate
    FROM myTable m
    GROUP BY Forename, Surname
    

    SELECT Id, Forename, Surname, SomeDate
    FROM myTable m
    WHERE m.Id = (SELECT TOP 1 Id FROM myTable mt WHERE mt.Forename = m.Forename AND mt.Surname = m.Surname
        ORDER BY m.SomeDate DESC)
    

    对于一个datatable示例,您基本上会做相同的事情。

    var recs = from record in dataTable
               where record.Id == 
                   (from rec in dataTable
                    where rec.Forename == record.Forename && rec.Surname == record.Surname
                    orderby rec.SomeDate descending
                    select rec.Id).First()
               select record;