计算总和给出42的不同数字的组合

时间:2017-04-05 08:07:57

标签: sql sql-server

我需要创建一个包含2列的临时表“Number_game”:Digit_number和Letter_number。将表中的值从1(一)插入到20(二十)。

我如何计算总和给出42的不同数字的组合?

 Select nb.Digit_number, ng.Digit_number
 from #Number_game as nb
 join #Number_game as ng on nb.Digit_number = ng.Digit_number
 where nb.Digit_number + ng.Digit_number =42;

我不知道如何采取更多的值来得到42个......

这是我插入的数据:

 INSERT INTO #Number_game(Digit_number, Letter_number)
Values (1,'one'),
(2,'two'),
(3,'three'),
(4,'four'),
(5,'five'),
(6,'six'),
(7,'seven'),
(8,'eight'),
(9,'nine'),
(10,'ten'),
(11,'eleven'),
(12,'twelve'),
(13,'thirteen'),
(14,'fourteen'),
(15,'fifteen'),
(16,'sixteen'),
(17,'seventeen'),
(18,'eighteen'),
(19,'nineteen'),
(20,'twenty');

1 个答案:

答案 0 :(得分:2)

您想要CROSS JOIN

With CTE as
(
select a1.digitnumber as n1, 
       a2.digitnumber as n2, 
       a3.digitnumber as n3
from number_game a1
cross join number_game a2
cross join number_game a3
)
select *
from CTE
where n1 + n2 + n3 = 42