Click here to Skip to main content
15,923,852 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Suppose I have two tables: PAYTYPE and PAYDETAILS:
PAYTYPE have fields like PayTypeId, PayType
PAYDETAILS have fileds like EmpCode, PayTypeId, Amount

Now I want to get seperate columns for each PayType with total - for an employee
Eg:
EmpCode, Basic, HRA, Other Allownces Total
Posted

You need to use PIVOTS

SQL
--Temp tables with data for testing
DECLARE @PayType TABLE ( PayTypeId INT, PayType VARCHAR(30))
DECLARE @PayDetails TABLE (EmpCode INT, PayTypeId INT, Amount Float)

INSERT INTO @PayType VALUES (1, 'Basic')
INSERT INTO @PayType VALUES (2, 'HRA')
INSERT INTO @PayType VALUES (3, 'Other Allownces')


INSERT INTO @PayDetails VALUES (1, 1, '12000')
INSERT INTO @PayDetails VALUES (1, 2, '6000')
INSERT INTO @PayDetails VALUES (1, 3, '3200')
INSERT INTO @PayDetails VALUES (2, 1, '5000')
INSERT INTO @PayDetails VALUES (2, 2, '3000')
INSERT INTO @PayDetails VALUES (2, 3, '1200')


--Query using Pivots
SELECT EmpCode, [Basic], [HRA], [Other Allownces], ([Basic]+ [HRA]+[Other Allownces]) Total
FROM (SELECT EmpCode, PayType, Amount
FROM @PayType pt
JOIN @PayDetails pd ON pt.PayTypeId = pd.PayTypeId) As Source
PIVOT(MAX(Amount) FOR PayType IN ([Basic], [HRA], [Other Allownces]) )AS p


Result

SQL
EmpCode Basic  HRA  Other Allownces Total
------- ----- ----- --------------- ----
1       12000 6000  3200            21200
2       5000  3000  1200            9200

Learn more about PIVOTS http://msdn.microsoft.com/en-us/library/ms177410.aspx[^]
 
Share this answer
 
Hi,

Check This Out

SQL
Select * from PAYTYPE , PAYDETAILS Where 1 = 2


Hope This Helps You...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900