sql - 如何进行区分大小写的 GROUP BY?

标签 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

最佳答案

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

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

关于sql - 如何进行区分大小写的 GROUP BY?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10952696/

相关文章:

sql - ActiveRecord 的查找方法?帮助加入模型

mysql - 外键:简单查询不起作用

sql-server-2008 - 在sql查询中需要帮助

sql - 从数据库中获取玩家排名

mysql - 我需要优化以下sql查询

sql - 我怎样才能避免额外的内部连接来优化这个查询?

c# - 使用 TransactionScope 时出现异常 "The operation is not valid for the state of the transaction"

sql-server - SQL Server 中时态表之间的数据同步

sql - 组 SQL 中的最新条目

mysql - 根据现有列中的值在新列中插入值