Friday, April 9, 2010

Difference between JOINS and UNION in SQL

In this post, I have given the difference between the use of Joins and the use of Union keyword in SQL.

I have a table named Table1 with Severity, Response SLA and Resolution SLA as its columns. Now I need to take the number of issues for both Response SLA and Resolution SLA based on Severity.

1. Using Inner join:

SELECT A.[Severity],A.[ResponseSLA],A.[Count],B.[ResolutionSLA],B.[Count] FROM
(
SELECT [Severity],[ResponseSLA], Count(1) As [Count] FROM Table1
WHERE GroupID = 4 AND [Month] = 'Mar - 2010'
GROUP BY [Severity],[ResponseSLA]
) A
INNER JOIN
(
SELECT [Severity],[ResolutionSLA], Count(1) As [Count] FROM Table1
WHERE GroupID = 4 AND [Month] = 'Mar - 2010'
GROUP BY [Severity],[ResolutionSLA]
) B
ON A.[Severity] = B.[Severity]
Order By A.[Severity]

The above query fetches the following result:

Severity

ResponseSLA

Count

ResolutionSLA

Count

Sev2

Not Met SLA

1

Not Met SLA

1

Sev3

Met SLA

29

Met SLA

31

Sev3

Not Met SLA

2

Met SLA

31

Sev4

Met SLA

597

Met SLA

613

Sev4

Not Met SLA

16

Met SLA

613


Note: You can replace "SELECT A.[Severity],A.[ResponseSLA],A.[Count],B.[ResolutionSLA],B.[Count] FROM" With "SELECT * FROM" and fetch all the columns.

2. Using Union:

Consider you need to calculate the total count. Then you should query as below.

SELECT * FROM
(
SELECT [Severity],[ResponseSLA], Count(1) As [Count] FROM Table1
WHERE GroupID = 4 AND [Month] = 'Mar - 2010'
GROUP BY [Severity],[ResponseSLA]
) A
UNION
(
SELECT 'Total' [Severity],'' [ResponseSLA], Count(1) As [Count] FROM Table1
WHERE GroupID = 4 AND [Month] = 'Mar - 2010'
)

The above query fetches the following result:

Severity

ResponseSLA

Count

Sev2

Not Met SLA

1

Sev3

Met SLA

29

Sev3

Not Met SLA

2

Sev4

Met SLA

597

Sev4

Not Met SLA

16

Total


645


Note: In UNION, the number of columns and the column names should match. In this case, the columns of both A & B should match each other.

Hope you understood the difference. Joins always add the columns to the left and the union statements add the columns to the bottom of the result grid.

No comments:

Post a Comment

Flipkart.com

  Flipkart, founded by the Bansals in 2007 is now being headed by Kalyan Krishnamurthy since 2016. A Billion dollar firm with more than 70 m...