如何检索两个数字之间的最大值并迭代

时间:2016-06-13 08:12:30

标签: sql sql-server

我有一个数字表,其中只包含一个值为1的NumberID,直到22。

我想在数字表上对自己执行CROSS JOIN,以便它在数字0之间迭代(不在Number表和5中)。这应输出所有可能的分数。

E.g

0-0
0-1
0-2
0-3
0-4
0-5
1-0
1-1
1-2
1-3
1-4
1-5
2-0

我需要做些什么才能工作?

INSERT INTO dbo.Score(Result)
SELECT cast(n.NumberID AS VARCHAR (10)) + ' - ' + cast(nn.NumberID AS VARCHAR (10)) AS Result
FROM dbo.Number n
CROSS JOIN dbo.Number nn
ORDER BY n.NumberID, nn.NumberID

2 个答案:

答案 0 :(得分:1)

您可以选择数字1到6并减去1以获得0到5。

INSERT INTO dbo.Score(Result)
SELECT cast(n.NumberID-1 AS VARCHAR (10)) + ' - ' + cast(nn.NumberID-1 AS VARCHAR (10)) AS Result
FROM dbo.Number n
CROSS JOIN dbo.Number nn
WHERE n.NumberID <= 6 AND nn.NumberID <= 6
ORDER BY n.NumberID, nn.NumberID

答案 1 :(得分:1)

你已经过了一半..只需在你的数字表中添加0,你就不需要订购了,这只是一个没有任何优势的开销

;With cte
as
(
select 0 as n
union all
select numberid from dbo.number
)
Insert into dbo.result
SELECT cast(n.NumberID AS VARCHAR (10)) + ' - ' + cast(nn.NumberID AS VARCHAR (10)) AS Result
FROM cte  n
CROSS JOIN cte  nn