SQL: how to get all the distinct characters in a column, across all rows

后端 未结 5 466
旧巷少年郎
旧巷少年郎 2020-12-30 03:39

Is there an elegant way in SQL Server to find all the distinct characters in a single varchar(50) column, across all rows?

Bonus points if it can be done without cur

5条回答
  •  感情败类
    2020-12-30 04:14

    Use this (shall work on any CTE-capable RDBMS):

    select x.v into prod from (values('product1'),('widget2'),('nicknack3')) as x(v);
    

    Test Query:

    with a as 
    (
        select v, '' as x, 0 as n from prod 
        union all
        select v, substring(v,n+1,1) as x, n+1 as n from a where n < len(v)
    )
    select v, x, n from a -- where n > 0
    order by v, n
    option (maxrecursion 0)
    

    Final Query:

    with a as 
    (
        select v, '' as x, 0 as n from prod 
        union all
        select v, substring(v,n+1,1) as x, n+1 as n from a where n < len(v)
    )
    select distinct x from a where n > 0
    order by x
    option (maxrecursion 0)
    

    Oracle version:

    with a(v,x,n) as 
    (
        select v, '' as x, 0 as n from prod 
        union all
        select v, substr(v,n+1,1) as x, n+1 as n from a where n < length(v)
    )
    select distinct x from a where n > 0
    

提交回复
热议问题