SQL Server从表列字段创建虚拟表或视图

时间:2014-06-04 10:09:36

标签: sql sql-server-2008

我有下表。

EmploeeID | SalaryMonth | Basic | HRA | TravAllowance | Bonus |

1---------| May-2014 ---| 1000  | 500 --| 100 -------------| 200 ---|

现在我想创建一个具有以下格式的虚拟表或视图。

EmployeeID         | SalaryMonth  | SalaryType ...........| Amount


1..................| May-2014.....| Basic..................| 1000

1..................| May-2014.....| HRA....................|  500

1..................| May-2014.....|TravAllowance...........| 100

1..................| May-2014.....| Bonus..................| 200

如何创建存储过程以返回上面的虚拟或临时表。

1 个答案:

答案 0 :(得分:0)

您正在寻找的是Unpivot功能。

参见以下示例:

create table tempTable (
  EmployeeID int
, SalaryMonth date
, Basic money
, HRA money
, TravAllowance money
, Bonus money
)

insert into tempTable (EmployeeID, SalaryMonth, Basic, HRA, TravAllowance, Bonus)
values (1, '01-04-2014', 1000, 500, 100, 200)


select
  EmployeeID
, SalaryMonth
, SaleryType
, Amount
from (
   select
     EmployeeID
   , SalaryMonth
   , Basic
   , HRA
   , TravAllowance
   , Bonus
   from tempTable
) p
UNPIVOT (Amount FOR SaleryType in (Basic, HRA, TravAllowance, Bonus)
) as unpvt