I have face a problem to re-format a sql table. The original table can be regard as in following format
index1 index2 item1 item2
01 001 10 100
02 001 10 100
...
01 002 20 200
02 002 20 200
...
and I want to re-format it into table like
index2 01item1 01item2 02item1 02item2 ...
001 10 100 10 100 ...
002 20 200 20 200 ...
...
index 1 and index 2 can mean any index except for primary key (for example i can call them color {red, yellow, blue} and shape {square, circle, bar},) and items indicate to of some certain type (in this example you can say a red circle), what data does that contains (for instance, item1 means weight and data is 80, item2 means height and data is 100, etc.)
I have looked at the following questions (Efficiently convert rows to columns in sql server), I believe my solution should exists in there but still could not get it, since I can't understand how to use pivot, and also I think my case is even complex than that.
It is safe to make assumption that the total number of index exists in index 1 are the same in all kinds of index2 (that is say, if there are 10 index1 in 001, than there will be 10 index 1 in 002 as well)
(hopefully it will not make people even more confuse about my question) so in the end I want to run a query looks like:
string builder sb = new string builder;
foreach(int indexNo2 in index2){
foreach(int indexNo1 in index1{
sb.append("select item1 as" + indexNo1+"item01, item2 as" +indexNo2+"item02
where index1 =" + indexNo1 + " and index2 =" + indexNo2 + "inner join");
}
sb.append("unit"+endl);
}
However this is just how I want to make the result look like, does not mean I really want to build such a long query at the end of day. PS. Even though I tried to write a c# suitcode to build a query, I want to find a solution in sql to re-format the table