T-SQL用于将2列的值合并为一个带有“replicate”的值

时间:2009-04-06 22:22:36

标签: sql sql-server sql-server-2008

有一个表格的值如下:

Sets | Reps
-----+------
2    | 10
3    | 15
3    | 12
4    | 8

我需要在SELECT语句中将这两个值组合成一个,所以我可以得到

SELECT ... AS Reps FROM Table

Reps
------------
10,10
15,15,15
12,12,12
8,8,8,8

任何想法如何做到这一点?

测试脚本:

DECLARE @Test TABLE ([Sets] INT, [Reps] INT);

INSERT INTO @Test VALUES (2, 10);
INSERT INTO @Test VALUES (3, 15);
INSERT INTO @Test VALUES (3, 12);
INSERT INTO @Test VALUES (4, 8);

SELECT [Sets], [Reps] FROM @Test;

// Here is an answer by tpdi:
SELECT CAST([Reps] AS VARCHAR) +
       REPLICATE(',' + CAST([Reps] AS VARCHAR), [Sets] - 1)
       AS [Reps] FROM @Test;

3 个答案:

答案 0 :(得分:2)

像这样:

select substring(replicate(','+cast(Reps as varchar),Sets),2,8000) as Reps
from Table

答案 1 :(得分:2)

select cast(reps as varchar)+ replicate(','+ cast(reps as varchar),sets - 1) 从表

答案 2 :(得分:0)

选择SUBSTRING(REPLICATE(CAST([Reps] as varchar)+',',[Sets]),          0,               LEN(REPER(CAST([Reps] as varchar)+',',[Sets]))                   )作为[代表] 来自@Test