Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
As I'm going to perform sql query, I doesnt get data accordingly. Let me show you example

This my table structure
nId nCompanyId nEmpId sComp dAmt
1 1 101 Salary 50000
2 1 101 TDS 10000
3 1 101 PF 5000
4 1 201 Salary 25000
5 1 201 TDS 6000
6 1 201 PF 2000

I want output like
nId nCompanyId nEmpId Salary TDS PF
1 1 101 50000 10000 5000
2 1 201 25000 6000 2000

What I have tried:

SELECT p.*
FROM Form16_temp
PIVOT(
MAX([dAmt])
for [sComp] IN ([Salary],[TDS],[PF])
) as P


I got output like
nId nCompanyId nEmpId Salary TDS PF
1 1 101 50000 Null Null
2 1 101 Null 10000 Null
3 1 101 Null Null 5000
4 1 201 25000 Null Null
5 1 201 Null 6000 Null
6 1 201 Null Null 2000
Posted
Updated 26-Apr-16 1:37am
v5
Comments
Patrice T 26-Apr-16 7:00am    
did you forget to ask for grouping ?
GT1335 26-Apr-16 7:02am    
I've tried but not get answer,

1 solution

Try this query

SQL
SELECT  nCompanyId, nEmpId, sum(Salary) Salary, sum(TDS) TDS,sum(PF) PF
FROM Form16_temp
PIVOT(
MAX([dAmt])
for [sComp] IN ([Salary],[TDS],[PF])
) as P
group by nCompanyId, nEmpId



Ashish Nigam
 
Share this answer
 
v2
Comments
GT1335 26-Apr-16 7:27am    
Not working
Nigam,Ashish 26-Apr-16 7:29am    
what is the output you are getting. with new query
GT1335 26-Apr-16 7:32am    
Same Output, Not grouping null values

nId nCompanyId nEmpId Salary TDS PF
1 1 101 50000 Null Null
1 1 101 Null 10000 Null
1 1 101 Null Null 5000
Nigam,Ashish 26-Apr-16 7:41am    
Remove "Nid" from query because it is unique number. Try below query:

SELECT nCompanyId, nEmpId, sum(Salary) Salary, sum(TDS) TDS,sum(PF) PF
FROM Form16_temp
PIVOT(
MAX([dAmt])
for [sComp] IN ([Salary],[TDS],[PF])
) as P
group by nCompanyId, nEmpId
GT1335 27-Apr-16 1:03am    
Thanks @Member3715253, Its working perfectly.

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