Creating a new table from two existing tables with every combination possibility

那年仲夏 提交于 2019-12-31 00:34:13

问题


I have two temporary tables #a and #b both filled with integer values. Let's say they both contain 10 rows with values 1-10.

I want to create a third temporary table #c that contains every possible combination of a and b. So it would have 100 rows total with (1,1), (1,2) ... (10, 10). How would I go about doing this in SQL. The implementation I'm using is SQL Server 2012.


回答1:


I think you can just do

SELECT * INTO #c FROM #a,#b



回答2:


Cross join will get all combinations

SELECT a.Col
, b.Col
FROM TableA a
CROSS JOIN TableB b



回答3:


BEGIN
DECLARE @a TABLE(x INT)
DECLARE @b TABLE(x INT)
INSERT INTO @a VALUES (1), (2)
INSERT INTO @b VALUES (1), (2)
select * from @a,@b
END



回答4:


There are certainly other correct answers here but I'll add the best elements of them together to answer the question completely:

select a.Col as ColA    -- Give the columns a name for the destination
    , b.Col as ColB
into #c                 -- Generates destination temp table #c
from #a as a
    cross join #b as b  -- Cross join is the preferred syntax
order by a.Col, b.Col   -- Optional but often helpful (aesthetic, identities, indexing, etc)

So yes, when you want a cartesian product, use a cross join.



来源:https://stackoverflow.com/questions/13056673/creating-a-new-table-from-two-existing-tables-with-every-combination-possibility

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!