Solved

Sql Query to pivot multiple rows to one row and add columns

Posted on 2012-12-30
6
446 Views
Last Modified: 2013-02-22
I have a table that looks like this (there are about 140 employee ids)

EmpID  |  EarnID  |  Current_Amount  |  Current_Hours
1136          401KM          25.49                          16
1136          401KT            118.97                       16
1151          401KM           10.00                          8
1151          401KT             15.00                         8
200            401KM            13.00                         2
200            401KT              0                               2

i would like it to look like this. . .

EmpID  |  Current_Hours  |  401KM  |  401KT
1136          16                             25.49          118.97
1151           8                              10.00          15.00
200             2                               13.00          0.00

 I have tried a few different queries with no luck. . .

Hoping someone can help.

TIA,

Faunna
0
Comment
Question by:DannerCorp
6 Comments
 
LVL 13

Expert Comment

by:F Igor
ID: 38731628
The following query expands the original table with separated data, and labeled using the EarnID value.

SELECT 
t1.empid, t1.current_hours, t1.current_amount as 401KM, t2.current_amount as 401KT
FROM  Table1 t1 
LEFT JOIN Table1 t2
ON t1.emp_id=t2.emp_id AND t2.EarnID='401KT'
WHERE
t1.EarnID='401KM'

Open in new window

0
 

Author Comment

by:DannerCorp
ID: 38731799
Thank you.  I think we almost got it. . but there is an error:
Incorrect syntax near '401' says it cannot be bound.

Here is the query with the table name.  sorry, I missed that at first.
401KM is 401k-Match and 401KT is 401k-Trade.  I shortened it in the first email.

SELECT
t1.EMP_ID, t1.CURRENT_HOURS, t1.CURRENT_AMOUNT as 401K-MATCH, t2.CURRENT_AMOUNT as 401K-TRAD
FROM PROC_EMP_PAYDETAIL t1
LEFT JOIN PROC_EMP_PAYDETAIL t2
ON t1.EMP_ID=t2.EMP_ID AND t2.EARN_ID='401K-TRAD'
WHERE
t1.EARN_ID='401K-MATCH'

TIA again.
0
 
LVL 75

Expert Comment

by:Anthony Perkins
ID: 38731856
You are missing square brackets around 401K-MATCH and 401K-TRAD as in (no points please):
SELECT  t1.EMP_ID,
        t1.CURRENT_HOURS,
        t1.CURRENT_AMOUNT AS [401K-MATCH],
        t2.CURRENT_AMOUNT AS [401K-TRAD]
FROM    PROC_EMP_PAYDETAIL t1
        LEFT JOIN PROC_EMP_PAYDETAIL t2 ON t1.EMP_ID = t2.EMP_ID
                                           AND t2.EARN_ID = '401K-TRAD'
WHERE   t1.EARN_ID = '401K-MATCH' 

Open in new window

0
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 

Author Comment

by:DannerCorp
ID: 38733851
ok thank you : )  Before I saw your email, I figured out to put MAtch401k and Match401kTrade and that worked too.

There are two more pieces to the query that I'm wondering if you could help me with. . .
I'm sorry, I'm just learning SQL to the extent of linking tables . . .I know access like the back of my hand, but we are using SQL at my new company and I'm learning on the fly.

1.) Current_Hours is coming up blank because it is grabbing the line with the 401K-MATCH or 401K-TRADE. . This should really be a sum of all hours for that employee.  (another line item in the table.)    Current Hours + Current_OT_Hours - see below

EmpID  |  EarnID  |  Current_Amount  |  Current_Hours    |Current_OT_HOURS
1136          401KM          25.49                          0                                      0
1136          401KT            118.97                       0                                      0
1136          FLOOR          9.14                             80                                    22

Would this be a third table reference t3?

So it would look like this . .

EmpID  |   Total_Hours  |  401K-Match  |  401K-Trade
11                    102                      25.49          118.97

2) And last but not least. . .The Employee needs his personal information from another table EMPLOEE

I need to link Employee table to t1? t1.EMPID = Employee.EMPID and grab LASTNAME . .

All on one line like this. . .

EmpID  |  EmpLastName|  Total_Hours  |  401K-Match  |  401K-Trade
1136            Ash                     102                      25.49          118.97
0
 
LVL 2

Expert Comment

by:harshada_sonawane
ID: 38734122
try this

SELECT  e.emp_id,e.name, Total_Hours ,[401K-Match] ,[401K-Trade] from

(
select emp_id,sum([401KM])+sum([401KT]) Total_Hours ,
sum([401KM]) as [401K-Match] ,sum([401KT]) as  [401K-Trade]
from
(select * FROM emp_det)AS mytable
 pivot
 (
 sum(Current_hours) FOR earnid IN ([401KM],[401KT])
 ) as  pvt  GROUP BY pvt.emp_id
 
 ) p
 
 INNER JOIN EMPLOEE e ON e.emp_id=p.emp_id
0
 
LVL 8

Accepted Solution

by:
rpkhare earned 400 total points
ID: 38734875
The above suggested solutions work when you desire only two fixed columns i.e., 401KM and 401KT.

Just in case your table grows and you have new values in EarnID column and you want your query to automatically handle those new values as columns, try this dynamic query:
IF OBJECT_ID('tempdb..#Results',N'U') IS NOT NULL
DROP TABLE #Results

select empid,earnid,current_amount,current_hours into #Results from <your_table_name>

declare @cols nvarchar(max)
declare @sql1 nvarchar(max)

select @Cols = stuff((select ', ' + quotename(EarnId)
from (select distinct top 100 earnid
as EarnId from #Results ORDER BY earnid) X
ORDER BY EarnId FOR XML PATH('')),1,2,'')

set @sql1 = 'SELECT * FROM #Results PIVOT (max(earnid) FOR earnid IN (' + @Cols +'))pvt'
execute (@sql1)

Open in new window

0

Featured Post

Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction SQL Server Integration Services can read XML files, that’s known by every BI developer.  (If you didn’t, don’t worry, I’m aiming this article at newcomers as well.) But how far can you go?  When does the XML Source component become …
I have a large data set and a SSIS package. How can I load this file in multi threading?
Via a live example, show how to setup several different housekeeping processes for a SQL Server.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now