How to generate all possible data combinations in SQL?

前端 未结 3 1459
日久生厌
日久生厌 2020-12-10 10:05

I\'m developing a shop web site. I have a database table, ProductOption, that represents the various options that are applicable to a product (Sizes, Colour

相关标签:
3条回答
  • 2020-12-10 10:22

    in SQLServer you can use CUBE Operator, that return a resultset with all combination... but I don't know if you meaning that...

    Hope this helps

    Nicola

    0 讨论(0)
  • 2020-12-10 10:28
    SELECT PO1.Value, PO2.Value, PO3.Value
    FROM ProductOption PO1, ProductOption PO2, ProductOption PO3 
    WHERE PO1.ProductOptionGroupID = 1
    AND PO2.ProductOptionGroupID = 2
    AND PO3.ProductOptionGroupID = 3
    
    0 讨论(0)
  • 2020-12-10 10:47

    Well, you are in kinda of a problem there, specially if you don't know wich groups are attached to wich products ahead of time. It appears to me that you are gonna need two of the biggest things a try to avoid in sql: cursors, and dynamic sql. Before using the following solution, you should take a look at this link The Curse and Blessings of Dynamic SQL. Then, you can try this:

    DECLARE @ProductId INT, @Query NVARCHAR(MAX), @ProductOptionGroupId INT
    SET @ProductId = 1
    SET @Query = ''
    
    DECLARE CC CURSOR FOR
    SELECT DISTINCT ProductOptionGroupId
    FROM YourTable
    WHERE ProductId = @ProductId
    
    OPEN CC
    FETCH NEXT FROM CC INTO @ProductOptionGroupId
    WHILE @@FETCH_STATUS = 0
    BEGIN
        SET @Query = @Query + '(SELECT DISTINCT Value FROM YourTable WHERE ProductOptionGroupId='+CAST(@ProductOptionGroupId AS VARCHAR)+'AND ProductId='+CAST(@ProductId AS VARCHAR)+
                     +') AS Table' + CAST(@ProductOptionGroupId AS VARCHAR)+' CROSS JOIN '
    
        FETCH NEXT FROM CC INTO @ProductOptionGroupId
    END
    CLOSE CC
    DEALLOCATE CC
    SET @Query = 'SELECT * FROM ' + LEFT(@Query,LEN(@Query)-10)
    
    PRINT @Query
    EXEC sp_executesql @Query
    

    Let me know how it goes.

    0 讨论(0)
提交回复
热议问题