MS SQL Server:根据列的值创建序列

时间:2013-11-15 20:09:51

标签: sql sql-server

我有这张桌子:

表:城市

  City      NumberOfSchools
 ------------------------------
  SCL           3
  Blah          5
  Narf          2
          ....    

我可以使用什么查询(无论是否为TransactSQL)来创建表X?

表: X

  City      Sequence
 ------------------------------
  SCL           1
  SCL           2
  SCL           3
  Blah          1
  Blah          2
  Blah          3
  Blah          4
  Blah          5
  Narf          1
  Narf          2
          ....    

1 个答案:

答案 0 :(得分:4)

试试这个:

SELECT A.City, B.number Sequence
FROM Cities A
CROSS JOIN (SELECT *
            FROM master.dbo.spt_values
            WHERE type = 'P'
            AND number > 0) B
WHERE B.number <= A.NumberOfSchools

Here is an sqlfiddle让你尝试。