6

Please consider this table:

ID         Page          Line           C01          C02          C03        
---------------------------------------------------------------------
1          122            11             1            0            1
1          123            11             1            1            1
1          124            12             0            0            0
1          125            16             1            0            1
1          127            11             0            1            0

I want to convert this table to this one:

ID         Page          Line           City         Value
-----------------------------------------------------------
1          122            11            C01            1           
1          122            11            C02            0  
1          122            11            C03            1  
1          123            11            C01            1  
1          123            11            C02            1  
1          123            11            C03            1  
...

How I can do this in appropriate way?

0

5 Answers 5

9

Use UNPIVOT. Try something like:

SELECT ID, Page, Line, City, Value
FROM SourceTable
UNPIVOT
   (Value FOR City IN 
      (C01, C02, C03)
)AS unpvt;

Where 'SourceTable' is your source table name. (Note: I can't test this at the moment, so it may not be exactly right.)

Full details here: http://msdn.microsoft.com/en-us/library/ms177410(v=sql.105).aspx

Sign up to request clarification or add additional context in comments.

Comments

1

Below query should do your requirement.

SELECT ID, PAGE, LINE, "C01", C01 FROM TABLE
UNION 
SELECT ID, PAGE, LINE, "C02", C02 FROM TABLE
UNION
SELECT ID, PAGE, LINE, "C03", C03 FROM TABLE

2 Comments

I guess the idea must be clear in general, but: 1) In Transact-SQL, double quotes are used to delimit names (by default, anyway). To delimit string constants, single quotes are used. 2) UNION removes duplicate rows. Even if duplicates are unlikely (like in this case), the query plan might still include steps for removing them, which would most probably be a performance hit. Use UNION ALL instead. 3) Aliases should probably be provided for the last two columns.
Thank you Andriy for clarification. Appreciate it.
1

Pivot & UnPivot will solve the issue :)

follow the links:

Comments

1

You can achieve this by doing something like this in Linq to sql

Is Unpivot (Not Pivot) functionality available in Linq to SQL? How?

Comments

0

Do a self-join, once for each 1+Nth column. And create a cartesian table.

Self-join is joining the same table to itself. Match it by id, page and line.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.