gpt4 book ai didi

tsql - SQL Server在GROUP BY期间丢弃SPACE

转载 作者:行者123 更新时间:2023-12-04 07:05:51 25 4
gpt4 key购买 nike

看起来SQL Server(在2008 R2上尝试)正在RTRIM子句中的列上执行GROUP BY。有人注意到吗?我在这里想念什么吗?

这两个选择在下面的查询中返回相同的结果集,我认为情况并非如此。

declare @t table(Name varchar(100), Age int)
insert into @t values ('A', 20)
insert into @t values ('B', 30)
insert into @t values ('C', 40)
insert into @t values ('D', 25)
insert into @t values (' A', 21)
insert into @t values ('A ', 32)
insert into @t values (' A ', 28)

select
Name,
count(*) Count
from @t
group by Name

select
rtrim(Name) RtrimmedName,
count(*) Count
from @t
group by rtrim(Name)

请让我知道你的想法...

最佳答案

它实际上是相反的,但可观察到的效果是相同的。

比较两个不等长的字符串时,SQL的规则之一(标准,而不仅仅是SQL Server)是将较短的字符串用空格填充,直到长度相同为止,然后进行比较。

如果要避免感到惊讶,则需要在每个字符串的末尾添加一个非空格字符。

实际上,检查standard text,似乎有两个选项:

4.6 Type conversions and mixing of data types

...

When values of unequal length are compared, if the collating sequence for the comparison has the NO PAD attribute and the shorter value is equal to a prefix of the longer value, then the shorter value is considered less than the longer value. If the collating sequence for the comparison has the PAD SPACE attribute, for the purposes of the comparison, the shorter value is effectively extended to the length of the longer by concatenation of <space>s on the right.



但是我知道的所有SQL Server排序规则都是 PAD SPACE

关于tsql - SQL Server在GROUP BY期间丢弃SPACE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12834488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com