I have a single table looking like this:
Table extract
Owner | Attribute | value
----------------------------------------------------
10 | COLOR | BLUE
10 | COLOR | RED
10 | COLOR | GREEN
10 | SIZE | BIG
20 | COLOR | GREEN
20 | SIZE | MEDIUM
20 | MEMORY | 16G
20 | MEMORY | 32G
30 | COLOR | RED
30 | COLOR | BLUE
30 | MEMORY | 64G
Is there a SQL which will calculate a combination of all attribute with a single index (last column in the result):
Owner | Attribute | Value | Rule_No
10 | COLOR | BLUE | 1
10 | SIZE | BIG | 1
10 | COLOR | RED | 2
10 | SIZE | BIG | 2
10 | COLOR | GREEN | 3
10 | SIZE | BIG | 3
20 | COLOR | GREEN | 1
20 | SIZE | MEDIUM| 1
20 | MEMORY | 16G | 1
20 | COLOR | GREEN | 2
20 | SIZE | MEDIUM| 2
20 | MEMORY | 32G | 2
30 | COLOR | BLUE | 1
30 | MEMORY | 64G | 1
30 | COLOR | RED | 2
30 | MEMORY | 64G | 2
The rule number would be unique per owner (rule ‘1’ for owner ’10’ is not related to rule ‘1’ for owner ’20’.
I tried to use the SQL cross join, but the number of attributes is not fixed, then I cannot use it (one cross join per attribute is needed) and I want the combination to be new rows instead new columns.
I am trying to use Talend Open Studio - Data Integration to do it but a solution using only SQL would be better for me.
Do you really want the data in the form given in your question (which would then require further aggregation on
Rule_Noto be useful in most likely situations), or are you ultimately seeking to pivot it? That is, rules are joined together (with each attribute becoming its own column) as follows:One can pivot such data with a query as follows:
As the attribute list is dynamic, one can use a query to construct the above SQL from which one prepares and executes a statement:
See it on sqlfiddle.