使用公用表表达式太复杂了吗?

时间:2013-12-06 23:59:31

标签: sql

假设以下公用表表达式生成两个数字之间的所有整数(在这种情况下为1和9):

WITH numbers(n) AS
(
  SELECT 1 as n
  UNION ALL
  SELECT n+1 as n FROM numbers WHERE n < 9
)
select * from numbers

我有一个名为Levels的表:

SELECT * from Levels

Player  StartingLevel   EndingLevel
john     2              4
Ed       7              8

我希望CTE在每个玩家的范围内为每个难度级别返回一行,例如:

PLAYER CurrentLevel
John   2
John   3
John   4
Ed     7
Ed     8

可以用CTE完成吗?或者我只需要编写存储过程来执行此操作吗?

2 个答案:

答案 0 :(得分:2)

试试这个:

WITH playerlevels(player, level) AS
(
   SELECT player, startingLevel
   From Levels
   Union all 
   SELECT player, cast(p.level+1 as integer)
   from playerlevels p
     join Levels l 
         On p.player = l.player
   where p.level+1 <= l.EndingLevel
)
select * from playerlevels

答案 1 :(得分:0)

您可以使用BETWEEN

将CTE加入到关卡表中
WITH numbers(n) AS
(
  SELECT 1 as n
  UNION ALL
  SELECT n+1 as n 
  FROM numbers 
  WHERE n < 9
)
SELECT l.Player, n.n AS CurrentLevel
FROM numbers n
JOIN Levels l
  ON n.n BETWEEN l.StartingLevel AND l.EndingLevel

演示:SQL Fiddle