具有不区分大小写的值的SELECT / COUNT列

时间:2018-04-24 16:27:05

标签: sql sql-server

我有一个DB列,其中包含的值在未检查其大小写时可能相互匹配:

my_column
---------
foo
bar
BAR
baz

列定义如下所示:

[my_column]   NVARCHAR (15)   COLLATE SQL_Latin1_General_CP1_CS_AS NULL

当我这样选择时:

SELECT my_column FROM my_table ORDER BY my_column;

...我可以看到所有结果,但我只想看到LOWER()应用于所有值时重复的值,以及有多少dupes的计数。所以我的理想结果将是:

my_column | count
----------+-------
 bar      |  2

我假设此处需要GROUP BYHAVING,但我不确定您如何告诉SQL"找到与匹配的所有内容制作小写"。

5 个答案:

答案 0 :(得分:2)

这是你想要的吗?

DECLARE @tbl TABLE 
  ( 
     my_column VARCHAR(25) 
  ) 

INSERT INTO @tbl 
VALUES      ('foo'), 
            ('bar'), 
            ('BAR'), 
            ('baz') 

SELECT Lower(my_column) AS my_column, 
       Count(*)         AS count 
FROM   @tbl 
GROUP  BY Lower(my_column) 
HAVING Count(*) > 1 

返回:

my_column   count
bar         2

答案 1 :(得分:1)

这应该做的工作:

SELECT Lower(my_column), 
       Count(*) 
FROM   my_table 
GROUP  BY Lower(my_column) 
HAVING Count(*) > 1 

答案 2 :(得分:0)

试试这个:

SELECT 
    my_column,
    count(*) 
FROM 
(
    SELECT 
        lower(my_column) as my_column 
    FROM 
        my_table
) as t
ORDER BY 
    my_column
HAVING 
    COUNT(*) > 1;

答案 3 :(得分:0)

SELECT Lower(my_column) AS my_column, 
       Count(*) 
FROM   my_table 
GROUP  BY Lower(my_column) 
HAVING Count(Lower(my_column)) > 1; 

答案 4 :(得分:0)

这对我来说非常好

{ "example-package": "https://github.com/moment/moment.git" }