使GroupBy查询区分大小写

时间:2019-01-24 12:15:18

标签: sql-server group-by

我有桌子,上面有一些数据

Table User

我正在尝试像这样编写GroupBy查询

SELECT  [name] FROM [Example].[dbo].[User] Group By [Example].[dbo].[User].[name]

但它仅显示一条记录 Group By query

我需要获取所有三个记录,因为它们被寄存器分开了。如何编写区分大小写的GroupBy查询?

4 个答案:

答案 0 :(得分:0)

这是整理的事情。 CS表示区分大小写,CI表示不区分大小写。

我将向您展示一个示例:

USE YourDb;

WITH CS AS 
(
    SELECT 'CaseSensitive' COLLATE SQL_Latin1_General_CP1_CS_AS AS ColA 
)

SELECT * FROM CS WHERE ColA = 'casesensitive';

WITH CI AS 
(
    SELECT 'CaseSensitive' COLLATE SQL_Latin1_General_CP1_CI_AS AS ColA 
)

SELECT * FROM CI WHERE ColA = 'casesensitive'

答案 1 :(得分:0)

您需要将列的排序规则更改为区分大小写的排序规则。例如:

SELECT [name] COLLATE Latin1_General_100_CS_AS_SC;
       FROM [Example].[dbo].[User]
       GROUP BY [Example].[dbo].[User].[name] COLLATE Latin1_General_100_CS_AS_SC;

区分大小写的归类通常在名称中带有CS

要选择要使用的排序规则,可以使用以下方法找到列的排序规则:

SELECT c.collation_name
       FROM sys.columns c
            INNER JOIN sys.objects o
                       ON o.object_id = c.object_id
                          AND o.type = 'U'
            INNER JOIN sys.schemas s
                       ON s.schema_id = o.schema_id
       WHERE lower(s.name) = 'dbo'
             AND lower(o.name) = 'user'
             AND lower(c.name) = 'name';

一个很好的猜测是采用该排序规则,并将CI(对于大小写不敏感)替换为CS(如上所示)。

答案 2 :(得分:0)

process_response

然后您的查询代码可以保持现在的状态。

答案 3 :(得分:0)

这里的解决方案对,取决于您的目标。如果您需要大量区分大小写的版本,但又不想更改数据库/列的排序规则,则建议使用计算列:

USE Sandbox;
GO
--Alter the whole database
--ALTER DATABASE [Sandbox] COLLATE Latin1_General_CS_AI; --Commented out as unlikely to be the answer

CREATE TABLE dbo.[User] --I suggest a different name, USER is a reserved word in T-SQL
    (id int,
     [name] varchar(20)); --Name isn't reserved, but is a keyord, so you probably want to use a different name a again

INSERT INTO dbo.[User] ([id],
                        [name])
VALUES(1,'abc'),
      (1,'Abc'),
      (1,'ABC');
GO

--Current example
SELECT [name]
FROM dbo.[User]
GROUP BY [name];

--use COLLATE

SELECT [name] COLLATE Latin1_General_CS_AI AS [name]
FROM dbo.[User]
GROUP BY [name] COLLATE Latin1_General_CS_AI;
GO

--Alter the column's collation
--ALTER TABLE dbo.[User] ALTER [name] varchar(20) COLLATE Latin1_General_CS_AI; --Probably not the right solution either.

--Add a Collated calculated column    
ALTER TABLE dbo.[User] ADD name_CS AS [name] COLLATE Latin1_General_CS_AI PERSISTED;
GO

SELECT [name_CS] AS [name]
FROM dbo.[User]
GROUP BY [name_CS];
GO
--Cleanup
DROP TABLE dbo.[User];