SQL Server 2012:varchar列上的MAX无法按预期工作

时间:2022-06-20 08:48:46

I am using aggregates like MAX on varchar columns. When I execute a simple select on a varchar column, I get 4 characters value which is "övrö". In that column I found lots of values that are much bigger in length. My understanding is that it should return a value like "asdfsadfasdfasdfsadfsdafsdafsadfasdfsadfasdf".

我在varchar列上使用MAX这样的聚合。当我在varchar列上执行简单选择时,我得到4个字符值,即“övrö”。在该专栏中,我发现了许多长度更大的值。我的理解是它应该返回一个像“asdfsadfasdfasdfsadfsdafsdafsadfasdfsadfasdf”这样的值。

Please correct me if I am misunderstanding/misusing MAX as I have to use this concept in a complicated SQL to avoid duplicate records.

如果我误解/误用MAX,请纠正我,因为我必须在复杂的SQL中使用这个概念以避免重复记录。

If MAX on varchar gets top record based on alphabetical order, how come it still causing the duplicate values if I use it for specific columns (#2 and 3 as shown in the attached image. Red border area is showing duplicates, which should just be a single row.

如果varchar上的MAX根据字母顺序获得最高记录,那么如果我将其用于特定列(#2和3,如附图所示),它怎么仍会导致重复值。红色边框区域显示重复,应该只是单排。

SQL Server 2012:varchar列上的MAX无法按预期工作

EDIT - ISSUE RESOLVED

编辑 - 问题解决

The problem was that I was adding the string columns Aggregates in Group By clause, when removed, duplicates are gone!!!

问题是我在Group By子句中添加字符串列Aggregates,当删除时,重复项已经消失!

Thanks for the help.

谢谢您的帮助。

1 个解决方案

#1


1  

Min and max get the maximal values. For varchar, it's not the length, but imagine them as sorted alphabetically. Max takes the last element while min takes the first.

最小值和最大值获得最大值。对于varchar,它不是长度,而是将它们按字母顺序排序。 Max取最后一个元素,而min取第一个元素。

If you want to take the maximum length, you need max(length( column ))

如果你想取最大长度,你需要max(长度(列))

#1


1  

Min and max get the maximal values. For varchar, it's not the length, but imagine them as sorted alphabetically. Max takes the last element while min takes the first.

最小值和最大值获得最大值。对于varchar,它不是长度,而是将它们按字母顺序排序。 Max取最后一个元素,而min取第一个元素。

If you want to take the maximum length, you need max(length( column ))

如果你想取最大长度,你需要max(长度(列))