【问题标题】:Select all except duplicate columns unless the length of the column's string is longest选择除重复列之外的所有列,除非列的字符串长度最长
【发布时间】:2018-10-20 04:12:48
【问题描述】:

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

strWord、strWordType、strWordDescription

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

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

示例: myTable

  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

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 显示样本数据和预期结果
  • 好吧..随意帮助自己
  • @maSTAShuFu 添加示例
  • "在重复的情况下,我只想返回strWord长度最长的行。这应该只在strWordType相同的情况下生效。"在您的示例中,布鲁斯具有不同的 strWordType,但已消除了一个。怎么加起来?

标签: sql sql-server performance join select


【解决方案1】:

刚刚解决了-

SELECT MAX(mt.strWord),
       mt.strWordType,
       mt.strWordDescription


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

【讨论】:

  • 如果它解决了您的问题,您可以选择它作为接受的答案。
  • @CompSciFly 。 . .我看不出max() 与最长单词有什么关系,所以我看不出这如何解决您的问题。如果你想按字母顺序排列最后一个单词,那么你应该问另一个问题。
  • @GordonLinoff 在 SQL Server 中使用 max 允许我们按 strWordType 和 strWordDescription 进行分组,并且仍然选择 strWord。 order by 是按 strWord 的长度排序的。这完全符合预期。
  • @CompSciFly 。 . .这没有回答您提出的问题。
【解决方案2】:

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

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
                  );

【讨论】:

  • 感谢您的回答。虽然,这个在性能方面慢了大约 10 倍,所以我会选择另一个。
  • @CompSciFly 。 . .有趣的。与(description, strWordType, strword) 上的索引相比,性能如何?
  • 子查询造成89%的开销
  • 这个方法应该是最快的方法,索引在(description, strWordType, strword)上。
  • 我们无法在 strWord 上建立索引,因为我们并未尝试将所有这些都包括在内。对 description 和 wordType 进行索引是有效的,因为我们希望排除具有相同 description 和 wordType 但 strWord 更长的条目。
猜你喜欢
  • 2013-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-17
  • 1970-01-01
  • 2018-11-23
  • 1970-01-01
  • 2014-10-24
相关资源
最近更新 更多