根据月

时间:2015-11-05 08:17:20

标签: sql sql-server-2008 pivot unpivot

我有以下输入:

JAN_OLD FEB_OLD MAR_OLD APR_OLD MAY_OLD JUNE_OLD  JAN_NEW FEB_NEW MAR_NEW APR_NEW MAY_NEW JUNE_NEW
10        11       12      13      14       15       20      21      22      23      24      25

禁用的结果集如下:

JAN New OLD
FEB 20  10
MAR 21  11
APR 22  12
MAY 23  13
JUN 24  14

有人可以建议如何实现这个目标吗?

1 个答案:

答案 0 :(得分:3)

多个Union All或单个Cross Apply

SELECT months,old,new
FROM   Your_table
       CROSS apply (VALUES(jan_old,jan_new,'Jan'),
                          (FEB_OLD,FEB_new,'Feb'),
                          (MAR_OLD,MAR_new,'Mar'),
                          (APR_OLD,APR_new,'Apr'),
                          (MAY_OLD,MAY_new,'may'),
                          (JUNE_OLD,JUNE_new,'Jun'))
         cs (old, new, months) 

如果你不确定没有。然后你可能必须使用Dynamic sql