如何将列的值增加到其他列中的值的特定范围?

时间:2013-10-03 00:13:53

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

现有表格如下:

tmc         speed
ABC         55
DEF         55

我想使用SQL Server 2008中的现有表创建一个类似下面的表:

tmc            speed
ABC            55
ABC            56
ABC            57
ABC            58
ABC            59
ABC            60
DEF            55
DEF            56
DEF            57
DEF            58
DEF            59
DEF            60

我开发的代码没有向我显示我想要的确切结果。任何帮助将受到高度赞赏。

我用来解决问题的代码是:

; WITH mycte AS 
( SELECT [tmc_code], [speed] FROM table_1 
  UNION ALL 
  SELECT [tmc_code], [speed]+1 FROM table_1 WHERE [speed]+1 <=60 ) 
SELECT [tmc_code], [speed] FROM mycte 

2 个答案:

答案 0 :(得分:2)

你在找这样的东西吗?

;WITH mycte AS (
  SELECT 1 n
  UNION ALL
  SELECT n + 1 FROM mycte WHERE n < 100
)
SELECT tmc_code, speed + n - 1 speed
  FROM table1 CROSS JOIN mycte
 WHERE mycte.n BETWEEN 1 AND 6
 ORDER BY tmc_code, speed

输出:

| TMC_CODE | SPEED |
|----------|-------|
|      ABC |    55 |
|      ABC |    56 |
|      ABC |    57 |
|      ABC |    58 |
|      ABC |    59 |
|      ABC |    60 |
|      DEF |    55 |
|      DEF |    56 |
|      DEF |    57 |
|      DEF |    58 |
|      DEF |    59 |
|      DEF |    60 |

这是 SQLFiddle 演示

答案 1 :(得分:0)

考虑一个持久数字表it can have many uses,包括您目前的问题。

使用数字表,您可以执行以下操作:

SELECT
  t.tmc_code,
  speed = t.speed + n.Number
FROM table_1 AS t
INNER JOIN numbers AS n ON n.Number BETWEEN t.speed AND t.speed + 5
;