简体   繁体   中英

SQL Case Sensitive Group By

Intro

I have a table which is having a column "AccountCode" and other columns. There are few account codes which are same but differs being case-sensitive. Example:

AccountCode   OrderId
ABC           O001
ABC           O002
abc           O003
DEF           O004

Objective

I want a query to have a group by on AccountCode column and get respective count. Expected output should be like

ABC      2
abc      1
DEF      1

I have tried using COLLATE Latin1_General_CS_AS but unable to get desired result.

Below query doesn't provide a case-sensitive output

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

Assign the COLLATE also on the GROUP BY clause

select accountCode COLLATE Latin1_General_CS_AS, count(OrderId)  
from <<TableName>>  
group by accountCode COLLATE Latin1_General_CS_AS
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

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

INSERT INTO #Temp(AccountCode ,OrderId) SELECT 'ABC','O001' UNION ALL SELECT 'ABC','O002' UNION ALL SELECT 'abc','O003' UNION ALL SELECT 'DEF','O004'

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

ROLLBACK TRAN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM