如何计算字符串中的每个字符并以表格格式显示每个实例

时间:2013-09-01 17:05:24

标签: sql string count

我的表master_schedule

cable_no
D110772
D110773
D110774
D110775
D110776
D110777
D110778
D110779
D110880

我想创建一个循环,以便字符串中的每个字符都计算并显示

D 9
1 18
2 1
3 1
AND SO ON .......
我怎样才能修改下面提到的这些sql查询:
select (sum(LEN(cable_no) - LEN(REPLACE(cable_no, 'D', '')))*2) as FERRUL_qtyx2
from MASTER_schedule

2 个答案:

答案 0 :(得分:1)

这样的事情:

select substring(cable_no, n.n, 1) as letter, count(*) as cnt
from FERRUL_qtyx2 t cross join
     (select 1 as n union all select 2 union all select 3 union all select 4 union all
      select 5 union all select 6 union all select 7
     ) n
group by substring(cable_no, n.n, 1);

这将创建一个数字序列n,直到字符串的长度。然后,它会使用cross joinsubstring()来提取每个cable_no的第n个字符。

一般来说,这比执行union all七次要快。 union all方法通常会扫描表格7次。这将只扫描一次表。

答案 1 :(得分:0)

您可以使用recursive common table expression

with cte(symbol, cable_no) as (
    select
        left(cable_no, 1), right(cable_no, len(cable_no) - 1)
    from Table1

    union all

    select
        left(cable_no, 1), right(cable_no, len(cable_no) - 1)
    from cte
    where cable_no <> ''
)
select symbol, count(*)
from cte
group by symbol

=> sql fiddle demo

另一种方法(在Gordon Linoff解决方案之后制作):

;with cte(n) as (
    select 1
    union all
    select n + 1 from cte where n < 7
)
select substring(t.cable_no, n.n, 1) as letter, count(*) as cnt
from #Table1 as t
    cross join cte as n
group by substring(t.cable_no, n.n, 1);

=> sql fiddle demo