Click here to Skip to main content
15,885,767 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.8K   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 
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.