1

我的表 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
4

2 回答 2

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 joinandsubstring()提取每个 的第 n 个字符cable_no

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

于 2013-09-01T17:12:23.263 回答
0

您可以使用递归公用表表达式

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 小提琴演示

另一种方法(在 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 小提琴演示

于 2013-09-01T17:11:25.197 回答