SQL区分大小写

时间:2016-10-25 06:20:41

标签: sql sql-server collation

简介

我有一个表格,其中包含一个列" AccountCode"和其他专栏。几个帐户代码相同但不同区分大小写。 例如:

AccountCode   OrderId
ABC           O001
ABC           O002
abc           O003
DEF           O004

目的

我希望查询在AccountCode列上有一个组,并获得相应的计数。预期输出应该像

ABC      2
abc      1
DEF      1

我尝试过使用COLLATE Latin1_General_CS_AS但无法获得所需的结果。

以下查询并未提供区分大小写的输出

select accountCode COLLATE Latin1_General_CS_AS, count(OrderId) 
from <<TableName>> 
group by accountCode

3 个答案:

答案 0 :(得分:3)

也在GROUP BY子句上分配COLLATE

select accountCode COLLATE Latin1_General_CS_AS, count(OrderId)  
from <<TableName>>  
group by accountCode COLLATE Latin1_General_CS_AS

答案 1 :(得分:1)

create table #a
(
AccountCode varchar(10)  , OrderId varchar(10)
)
insert into #a values
('ABC','O001'),
('ABC','O002'),
('abc','O003'),
('DEF','O004')

select accountCode COLLATE Latin1_General_CS_AS, count(OrderId) from #a group by accountCode COLLATE Latin1_General_CS_AS

答案 2 :(得分:0)

BEGIN TRAN CREATE TABLE #Temp(AccountCode VARCHAR(100),OrderId VARCHAR(100))

INSERT INTO #Temp(AccountCode,OrderId) 选择&#39; ABC&#39;,&#39; O001&#39; UNION ALL 选择&#39; ABC&#39;,&#39; O002&#39; UNION ALL SELECT&#39; abc&#39;,&#39; O003&#39; UNION ALL SELECT&#39; DEF&#39;,&#39; O004&#39;

SELECT AccountCode COLLATE Latin1_General_CS_AS,COUNT(OrderId)FROM #Temp GROUP BY accountCode COLLATE Latin1_General_CS_AS

ROLLBACK TRAN