0

我有一张如下表

DECLARE @T TABLE(Data VARCHAR(MAX))
INSERT INTO @T
SELECT 'SQL' UNION ALL SELECT 'JOB'

需要如下输出,但不使用任何 UDF。

Data  String
------------
SQL   S,Q,L
JOB   J,O,B

请帮助我

4

4 回答 4

2

你当然可以 :)。也可以缩短...

DECLARE @T TABLE(Data VARCHAR(MAX))
INSERT INTO @T
SELECT 'SQL' UNION ALL SELECT 'JOB';    

With cte as
(
    Select Data, Len(Data) DataLength, 1 level
    From @t
    Union All 
    Select Data, DataLength - 1, level + 1
    From cte
    Where DataLength > 1 
),
cte2 as
(
    Select Data, SUBSTRING(Data, DataLength, 1) DataLetter, level
    From cte
),
cte3 as
(
    Select Data, 
        (
            SELECT DataLetter + ','
            FROM cte2 c
            Where c.Data = cte2.Data
            Order By level desc
            FOR XML PATH(''), TYPE

        ).value('.[1]', 'NVARCHAR(1000)') DataComa
    From cte2
    Group By Data
)
Select Data, substring(DataComa, 1, Len(DataComa) - 1) Data2
From cte3
于 2012-07-17T12:26:25.180 回答
1

派对迟到了,但这里有一个略短的版本:

DECLARE @T TABLE(Data VARCHAR(MAX));

INSERT INTO @T VALUES('SQL'),('JOB'),('FLOOB');

;WITH n AS (SELECT TOP (SELECT MAX(LEN(Data)) FROM @T) 
  n = ROW_NUMBER() OVER (ORDER BY [object_id]) FROM sys.all_objects
),
t AS (SELECT n, Data, Letter = SUBSTRING(t.Data, n.n, 1) FROM n
  INNER JOIN @T AS t ON SUBSTRING(t.Data, n.n, 1) > ''
)
SELECT Data, STUFF((SELECT ',' + letter FROM t AS t2
  WHERE t2.Data = t.Data ORDER BY t2.n FOR XML PATH(''), 
  TYPE).value(N'./text()[1]', N'varchar(max)'), 1, 1, '')
FROM t GROUP BY Data;

结果:

FLOOB   F,L,O,O,B
JOB     J,O,B
SQL     S,Q,L
于 2012-07-17T13:00:41.687 回答
0

使用 UDF 很容易做到。但是如果你想要没有UDF,我能想到的唯一一种方法是

像这样的东西

DECLARE @T TABLE(Data VARCHAR(MAX))
INSERT INTO @T
SELECT 'SQL' UNION ALL SELECT 'JOB'

select replace(replace(replace(data,'S','S,'),'Q','Q,'),'L','L,') from @T

在这里,您必须使用替换功能替换所有 26 个字符。即,“A”与“A”,“B”与“B”,......“Z”与“Z”,

于 2012-07-17T12:28:07.000 回答
0

使用我在此处用于 Initcap 函数的相同方法http://beyondrelational.com/modules/2/blogs/70/posts/10901/tsql-initcap-function-convert-a-string-to-proper-case.aspx

DECLARE @T TABLE(Data VARCHAR(MAX)) 
INSERT INTO @T 
SELECT 'SQL' UNION ALL SELECT 'JOB' 

select data,
        upper(replace(replace(replace(replace(replace(replace(replace(
        replace(replace(replace(replace(replace(replace(replace(
        replace(replace(replace(replace(replace(replace(replace(
        replace(replace(replace(replace(replace(
            ' '+data ,
        ' a','a,'),' b','b,'),'c','c,'),'d','d,'),'e','e,'),'f','f,'),
        ' g','g,'),' h','h,'),'i','i,'),'j','j,'),'k','k,'),'l','l,'),
        ' m','m,'),' n','n,'),'o','o,'),'p','p,'),'q','q,'),'r','r,'),
        ' s','s,'),' t','t,'),'u','u,'),'v','v,'),'w','w,'),'x','x,'),
        ' y','y,'),' z','z,')) as splitted_data
from
    @t
于 2012-07-17T12:47:21.010 回答