开发者

What is the most effective and flexible way to generate combinations in TSQL?

开发者 https://www.devze.com 2022-12-30 06:44 出处:网络
What is the most effective and flexible way to generate combinations in TSQL? With \'Flexible\', I mean you should be able to add easily combination rules. e.g.: to generate combinatories of \'n\' ele

What is the most effective and flexible way to generate combinations in TSQL? With 'Flexible', I mean you should be able to add easily combination rules. e.g.: to generate combinatories of 'n' elements, sorting, remove duplicates, get combinatories where each prize belongs to a different lottery开发者_如何学JAVA, etc.

For example, Having a set of numbers representing lottery prizes.

Number | Position | Lottery
---------------------------
 12    | 01       | 67
 12    | 02       | 67
 34    | 03       | 67
 43    | 01       | 89
 72    | 02       | 89
 33    | 03       | 89

(I include the position column because, a number could be repeated among different lottery's prizes)

I would like to generate combinatories like:

Numbers | Lotteries
-------------------
 12 12  | 67 67
 12 34  | 67 67
 12 34  | 67 67
 12 43  | 67 89
 12 72  | 67 89
 12 33  | 67 89

        .
        .
        .


This is called a CROSS JOIN:

SELECT
    CAST(T1.Number AS VARCHAR) + ' ' + CAST(T2.Number AS VARCHAR) AS Numbers,
    CAST(T1.Lottery AS VARCHAR) + ' ' + CAST(T2.Lottery AS VARCHAR) AS Lottery
FROM table1 T1
CROSS JOIN table1 T2
ORDER BY Numbers


The more complicated approach would be to use F# so that the user can write equations using a Domain Specific Language.

For an example of how to use F# you can see the final comment in this blog:

http://cs.hubfs.net/forums/thread/4496.aspx

The reason being because you will need to come up with an easy way to do the calculations, written by the user, but, the other option is to use C# and an Entity-Attribute-Value structure (http://en.wikipedia.org/wiki/Entity-attribute-value_model), so that you can have a flexible system where the user can create equations for different types of lotteries, or differing rules.

But all of these may be more overkill for what you need, depending on how much flexibility you really need.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号