How to do a case sensitive GROUP BY?

前端 未结 4 1236
南旧
南旧 2020-12-03 02:46

If I execute the code below:

with temp as
(
  select \'Test\' as name
  UNION ALL
  select \'TEST\'
  UNION ALL
  select \'test\'
  UNION ALL
  select \'test         


        
相关标签:
4条回答
  • 2020-12-03 03:15

    You need to cast the text as binary (or use a case-sensitive collation).

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

    Using a collation:

    Select Name Collate SQL_Latin1_General_CP1_CS_AS, COUNT(name)
    From temp
    Group By Name Collate SQL_Latin1_General_CP1_CS_AS
    
    0 讨论(0)
  • 2020-12-03 03:22

    In MySQL/MariaDB, if you don't want to use collations or casting to binary, just use:

    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)
    
    0 讨论(0)
  • 2020-12-03 03:28

    Simply:

    SELECT count(*), CAST(lastname as BINARY) AS lastname_cs 
    FROM names 
    GROUP BY lastname_cs; 
    
    0 讨论(0)
  • 2020-12-03 03:35

    You can use an case sensitive collation:

    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
    
    0 讨论(0)
提交回复
热议问题