简体   繁体   中英

SQL server creating a virtual table or view from a table column fields

I have the following table.

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

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

Now I want to create a virtual table or view which has following format.

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


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

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

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

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

How should I create a stored procedure to return above virtual or temporary table.

What you are looking for is the Unpivot function.

See following example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM