Click here to Skip to main content
15,891,645 members
Articles / Programming Languages / SQL
Tip/Trick

Using PIVOT and JOIN Together in SQL Server

Rate me:
Please Sign up or sign in to vote.
4.73/5 (12 votes)
23 Sep 2014CPOL 82.9K   288   12   4
Here we will see how to use PIVOT and JOIN together in SQL query

Introduction

When working with cross tab reporting, PIVOT is quite handy. But some time, we may need to use PIVOT and JOIN together. So here with a simple example, we would see how we can use these two things together.

Background

Let's say we have two tables where:

  • Employeemaster - Hold the basic information about employees:

  • Employeesalarydetails - Holds the salary structure details like basics and other others benefits (Transportation allowance, Overtimes, etc.).

  • Result - Now we want to create a query in a way that the result would be in the form of:

Tables And Data

Tables

SQL
/*create tables*/
CREATE TABLE Employeemaster(
    Empid BIGINT,
    EmpName VARCHAR(100)
)

CREATE TABLE Employeesalarydetails(
    Empid BIGINT,
    Component VARCHAR(100),
    Amount FLOAT,
)

Data

SQL
/*insert datas*/
INSERT 
    INTO Employeemaster
    VALUES (1, 'Emp1'),
    (2, 'Emp2'),
    (3, 'Emp3'),
    (4, 'Emp4')
INSERT 
    INTO Employeesalarydetails
    VALUES(2, 'Basic', 10000),
    (2, 'Hra', 1000),
    (2, 'TA', 750),
    (1, 'Basic', 20000),
    (1, 'Hra', 1000),
    (3, 'Basic', 6700),
    (3, 'Hra', 100),
    (4, 'Basic', 5000),
    (4, 'Hra', 1000)

PIVOT of Employeesalarydetails

The PIVOT of Employeesalarydetails is:

SQL
SELECT *
    FROM Employeesalarydetails
    PIVOT(
        SUM(Amount)
            FOR Component
            IN([Basic],[Hra],[TA])
    )AS DtlPivot

To start using PIVOT, check out http://www.codeproject.com/Tips/500811/Simple-Way-To-Use-Pivot-In-SQL-Query.

Now to get the required output, we only need to join Employeemaster table and this pivoted result.

JOIN Employeemaster and PIVOT-ed Result

Test live example http://www.sqlfiddle.com/#!3/ad5e6/2.

Using CTE

SQL
WITH Dtl
AS
(
    SELECT *
        FROM Employeesalarydetails
        PIVOT(
            SUM(Amount)
                FOR Component
                IN([Basic],[Hra],[TA])        -- pivot for [Basic],[Hra],[TA]
        )AS DtlPivot
)
SELECT Emp.*,
    COALESCE(Dtl.[Basic], 0) AS [Basic],    -- assigning names for [Basic],[Hra],[TA]
    COALESCE(Dtl.[Hra], 0) AS [Hra],
    COALESCE(Dtl.[TA], 0) AS [TA]
    FROM Employeemaster AS Emp
    LEFT JOIN Dtl ON Emp.EmpId = Dtl.EmpId

To know more about CTE, check out http://www.codeproject.com/Articles/275645/CTE-In-SQL-Server.

Without CTE

SQL
SELECT Emp.*,
    COALESCE(Dtl.[Basic], 0) AS [Basic],    -- assigning names for [Basic],[Hra],[TA]
    COALESCE(Dtl.[Hra], 0) AS [Hra],
    COALESCE(Dtl.[TA], 0) AS [TA]
    FROM Employeemaster AS Emp    
    LEFT JOIN
    (
        SELECT *
        FROM Employeesalarydetails
        PIVOT(
            SUM(Amount)
                FOR Component
                IN([Basic],[Hra],[TA])        -- pivot for [Basic],[Hra],[TA]
        )AS DtlPivot
    )AS Dtl
    ON Emp.EmpId = Dtl.EmpId

Find the necessary SQL in the attachment.

License

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


Written By
Bangladesh Bangladesh
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionwhat if data in rows is not fix Pin
mahesh chikhale15-Oct-16 9:59
mahesh chikhale15-Oct-16 9:59 
hi i have similar issue but data in main table is not fix . I have 3 table PayActiveSalary ,PayActiveAdditions and PayActiveDeductions and in that type Allowances are not fix they may vary for each company so I cant fix rows data as column name what i should do?
EmployeeID item ItemDescr amount
19 19 Basic Salary 4000
19 21 Housing 1000
19 20 Transportation 1000
19 22 Other Allowance 1000
91 19 Basic Salary 2500
91 20 Transportation 300
91 22 Other Allowance 400
136 19 Basic Salary 1000
136 22 Other Allowance 1500

additions

390 26 Adjustment 800
240 27 Special Allowance 4000
323 26 Adjustment 2399
391 26 Adjustment 800
217 26 Adjustment 233

deductions
EmployeeID item ItemDescr amount
135 4 Cash Advance 300
300 4 Cash Advance 400
235 4 Cash Advance 200
272 10 Tuition Fee 1725
323 10 Tuition Fee 2935

how i can apply pivot on this three table to get single resulttable.
GeneralMy Vote 5 Pin
Shemeemsha (ഷെമീംഷ)23-Sep-14 20:14
Shemeemsha (ഷെമീംഷ)23-Sep-14 20:14 
GeneralRe: My Vote 5 Pin
DiponRoy21-Jul-20 18:41
DiponRoy21-Jul-20 18:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.