Is there a way to perform a cross join or Cartesian product in excel?

筅森魡賤 提交于 2020-01-10 23:19:54

问题


At the moment, I cannot use a typical database so am using excel temporarily. Any ideas?

The


回答1:


You have 3 dimensions here: dim1 (ABC), dim2 (123), dim3 (XYZ).

Here is how you make a cartesian product of 2 dimensions using standard Excel and no VBA:

1) Plot dim1 vertically and dim2 horizontally. Concatenate dimension members on the intersections:

2) Unpivoting data. Launch pivot table wizard using ALT-D-P (don't hold ALT, press it once). Pick "Multiple consolidation ranges" --> create a single page.. --> Select all cells (including headers!) and add it to the list, press next.

3) Plot the resulting values vertically and disassemble the concatenated strings

Voila, you've got the cross join. If you need another dimension added, repeat this algorithm again.

Cheers,

Constantine.




回答2:


This article helped me perform a cross join in Excel:

http://www.excelguru.ca/blog/2016/05/11/cartesian-product-joins-for-the-excel-person/

It requires the Microsoft Add in Microsoft Power Query For Excel https://www.microsoft.com/en-us/download/details.aspx?id=39379




回答3:


Using VBA, you can. Here is a small example:

Sub SqlSelectExample()
'list elements in col C not present in col B
    Dim con As ADODB.Connection
    Dim rs As ADODB.Recordset
    Set con = New ADODB.Connection
    con.Open "Driver={Microsoft Excel Driver (*.xls)};" & _
           "DriverId=790;" & _
           "Dbq=" & ThisWorkbook.FullName & ";" & _
           "DefaultDir=" & ThisWorkbook.FullName & ";ReadOnly=False;"
    Set rs = New ADODB.Recordset
    rs.Open "select ccc.test3 from [Sheet1$] ccc left join [Sheet1$] bbb on ccc.test3 = bbb.test2 where bbb.test2 is null  ", _
            con, adOpenStatic, adLockOptimistic
    Range("g10").CopyFromRecordset rs   '-> returns values without match
    rs.MoveLast
    Debug.Print rs.RecordCount          'get the # records
    rs.Close
    Set rs = Nothing
    Set con = Nothing
End Sub



回答4:


Here is a very easy way to generate the Cartesian product of an arbitrary number of lists using Pivot tables:

https://chandoo.org/wp/generate-all-combinations-from-two-lists-excel/

The example is for two lists, but it works for any number of tables and/or columns.

Before creating the Pivot table, you need to convert your value lists to tables.




回答5:


Try using a CROSS JOIN. Read more at MSDN

You can use the expression CROSSJOIN(table1, table2) to create a cartesian product.



来源:https://stackoverflow.com/questions/26999604/is-there-a-way-to-perform-a-cross-join-or-cartesian-product-in-excel

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