피벗

2013-03-13 3 views
-1

당신이 날 나는이 SQL 출력 테이블을피벗

DateWeek Keep_1 This_1 Order_1 Keep_2 This_2 Order_2 Keep_1-Keep_2 This_1-This_2 Order_1-Order_2 
1/1/2013 9  8  7  6  5  4  3    3    3

이 다음

을 달성하고 당신은 내가 보는 바와 같이

RowOrder Column_1 Column_2 Column_1-Column_2 
Keep  9  6  3 
This  8  5  3 
Order 7  4  3

으로 바꿀 데 도움이 수 행의 순서를 유지하기 위해 사전 순으로 정렬 할 수 없습니다. 또한 함께 Keep_1 This_1 Order_1을 쌓아서 Keep_2 This_2 Order_2을 함께 사용하고 Column_1과 함께 Column_2

아이디어를 얻으려면 어떻게해야합니까?

감사

+0

를 참조하십시오

또한 데이터베이스에 UNION ALL 쿼리를 사용하여 수행 할 수 있습니다? – Kermit

답변

1

당신이 SQL 서버 2008+를 사용하는 경우, 당신은 CROSS APPLYVALUES를 사용할 수 있습니다

select c.roworder, 
    c.col1, 
    c.col2, 
    c.col3 
from yourtable t 
cross apply 
(
    values 
    ('Keep', Keep_1, Keep_2, Keep_1_Keep_2), 
    ('This', This_1, This_2, This_1_This_2), 
    ('Order', Order_1, Order_2, Order_1_Order_2) 
) c (roworder, col1, col2, col3) 

SQL Fiddle with Demo를 참조하십시오.

select 'Keep' RowOrder, 
    Keep_1 col1, 
    Keep_2 col2, 
    Keep_1_Keep_2 col3 
from yourtable 
union all 
select 'This' RowOrder, 
    This_1 col1, 
    This_2 col2, 
    This_1_This_2 col3 
from yourtable 
union all 
select 'Order' RowOrder, 
    Order_1 col1, 
    Order_2 col2, 
    Order_1_Order_2 col3 
from yourtable 

SQL Fiddle with Demo 사용하고있는 DBMS

+0

대단한 선출 후보가되는 +1 +1 – Kermit

+0

환상적 !! 정말로 환상적이다!! 대단히 감사합니다. – Selrac