我可以在SQL中的字段中选择不同的/分组字符吗?

时间:2009-10-21 10:01:03

标签: sql select group-by distinct character

我想运行一个查询,该查询对于给定字段将计算特定字符的实例。

例如,如果我有一个名为'Friends'的表,其中'Names'字段包含行:Edward,James,Mike。我得到输出:

A 2, D 2, E 3, 我1, 等等...

2 个答案:

答案 0 :(得分:2)

通用答案是您需要将每个名称拆分成一个组成字符的表格,然后计算这些名称。

您没有提到您正在使用的RDBMS。答案因数据库引擎而有所不同。

例如,这将适用于SQL 2005 +:

DECLARE @friends TABLE (NAMES VARCHAR(30))
DECLARE @maxLen INT

INSERT @friends (NAMES)
SELECT 'Edward'
UNION SELECT 'James'
UNION SELECT 'Mike'

SELECT @maxLen = MAX(LEN(NAMES)) FROM @friends

;WITH numsCte 
AS 
( 
        --dynamic numbers table. If you have a numbers table in your database
        --use that instead, as it will be more efficient.
        SELECT 1 AS n 
        UNION ALL 
        SELECT n+1 FROM numsCte 
        WHERE n < @maxLen
)
,charCTE
AS
( 
        --split the string into a dataset
        SELECT *
        FROM numsCte AS nm
        CROSS APPLY (SELECT NAMES, SUBSTRING(NAMES, n, 1) AS splitChar 
                     FROM @friends
                    ) AS st
        WHERE splitChar > ''
)
SELECT  UPPER(splitChar) AS letter
        ,COUNT(1) AS cnt
FROM charCTE
GROUP BY splitChar
ORDER BY splitChar

但几乎可以肯定,它不适用于任何其他数据库引擎。

答案 1 :(得分:0)

一种方法是使用临时表,并在WHILE循环中填充它:

declare @letters table (letter varchar(1))
declare @pos int
set @pos = 1
while 1=1
    begin
    insert into @letters
    select substring(name,@pos,1)
    from @names
    where len(name) >= @pos

    if @@rowcount = 0
        break

    set @pos = @pos + 1
    end

select letter, count(*)
from @letters
group by letter

另一种方法是在临时表中创建有效字符位置的列表,或者在此示例中,使用递归公用表表达式(CTE):

declare @maxLen int
select @maxLen = max(len(name)) from @names
;WITH CharPositions (i) AS  ( 
    select 1
    union all
    select i+1 
    from CharPositions
    where i < @maxLen
)
select substring(n.name,cp.i,1), count(*)
from @names n
inner join CharPositions cp on cp.i <= len(n.name)
group by substring(n.name,cp.i,1)

我已针对此数据集测试了代码示例:

declare @names table (name varchar(max))
insert into @names values ('abc')
insert into @names values ('def')
insert into @names values ('def')
insert into @names values ('g')
insert into @names values ('g')
insert into @names values ('g')