如何做一个区分大小写的GROUP BY?

时间:2012-06-08 16:30:51

标签: sql sql-server sql-server-2008 group-by

如果我执行以下代码:

with temp as
(
  select 'Test' as name
  UNION ALL
  select 'TEST'
  UNION ALL
  select 'test'
  UNION ALL
  select 'tester'
  UNION ALL
  select 'tester'
)
SELECT name, COUNT(name)
FROM temp
group by name

返回结果:

TEST   3
tester 2

有没有办法让小组区分大小写,以便结果如下:

Test   1
TEST   1
test   1
tester 2

4 个答案:

答案 0 :(得分:24)

您需要将文本转换为二进制文件(或使用区分大小写的排序规则)。

With temp as
(
  select 'Test' as name
  UNION ALL
  select 'TEST'
  UNION ALL
  select 'test'
  UNION ALL
  select 'tester'
  UNION ALL
  select 'tester'
)
Select Name, COUNT(name)
From temp
Group By Name, Cast(name As varbinary(100))

使用整理:

Select Name Collate SQL_Latin1_General_CP1_CS_AS, COUNT(name)
From temp
Group By Name Collate SQL_Latin1_General_CP1_CS_AS

答案 1 :(得分:17)

您可以使用区分大小写的排序规则:

with temp as
(
  select 'Test' COLLATE Latin1_General_CS_AS as name
  UNION ALL
  select 'TEST'
  UNION ALL
  select 'test'
  UNION ALL
  select 'tester'
  UNION ALL
  select 'tester'
)
SELECT name, COUNT(name)
FROM temp
group by name

答案 2 :(得分:7)

简单地:

SELECT count(*), CAST(lastname as BINARY) AS lastname_cs 
FROM names 
GROUP BY lastname_cs; 

答案 3 :(得分:0)

在MySQL / MariaDB中,如果您不想使用排序规则或转换为二进制,则只需使用:

SELECT MAX(name), COUNT(name)
FROM (
  select 'Test' as name
  UNION ALL
  select 'TEST'
  UNION ALL
  select 'test'
  UNION ALL
  select 'test'
  UNION ALL
  select 'tester'
  UNION ALL
  select 'tester'
) as tmp
group by MD5(name)