代码之家  ›  专栏  ›  技术社区  ›  CompSciFly

选择除重复列以外的所有列,除非列的字符串长度最长

  •  0
  • CompSciFly  · 技术社区  · 7 年前

    我有一个包含以下列的表:

    strWord、strWordType、strWordDescription

    我希望能够选择所有的行,除了那些有重复strWordDescription的行。在重复的情况下,我只想返回strWord长度最长的行。只有当strWordType相同时,此选项才会生效。

    注意:strWords/strWordType组合没有重复的行,只有特定strWordType的重复strworddescription。我想避免使用 Distinct

    示例: 我的表格

      strWord |    strWordType  |   strWordDescription |
    
      blue         2012               This is a color
      blue         2014               This is a color
      green        2012               This is a color
      ham          2014               This is a food
      chicken      2014               This is a food
    

    预期结果:

       strWord  |   strWordType   | strWordDescription
    
       green        2012            This is a color
       blue         2014            This is a color
       chicken      2014            This is a food
    
    2 回复  |  直到 6 年前
        1
  •  0
  •   Gordon Linoff    7 年前

    嗯。我想到了一个相关的子查询:

    select t.*
    from t
    where t.strword = (select top (1) t2.strword
                       from t t2
                       where t2.description = t.description and
                             t2.strWordType = t.strWordType
                       order by len(t2.strword) desc
                      );
    
        2
  •  0
  •   CompSciFly    6 年前

    刚刚解决了-

    SELECT MAX(mt.strWord),
           mt.strWordType,
           mt.strWordDescription
    
    
    FROM myTable mt
    GROUP BY mt.strWordType, mt.strWordDescription
    ORDER BY MAX(mt.strWord)