繁体   English   中英

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

[英]How to do a case sensitive 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

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

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

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

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

简单地:

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

在 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)

这适用于我的情况:

SELECT BINARY example FROM table GROUP BY BINARY example;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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