Click here to Skip to main content
15,908,901 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
hi
i have 4 tables

## table 1 ''Employee''
 ID | Name
----|----
 01 | A1
 02 | B1
 03 | C1
 04 | D1


## table 2 ''Location''
 ID | Location
----|----------
 01 | L1
 02 | L1
 03 | L3
 04 | L2



## table 3 ''Department''
 ID | Department
----|------------
 01 | D1
 02 | D1
 03 | D2
 04 | D3



## table 4 ''Salary''
 ID | Salary
----|--------
 01 | 1000
 02 | 2000
 03 | 1500
 04 | 2000


The output should come as

Location  |Department|Salary
----------|----------|-------
   L1     |   D1     |1000
   L1     |   D2     |2000
----------|----------|------
          |  Salary  |3000
----------|----------|-------
   L2     |   D3     |1500
   L2     |   D5     |2000
----------|----------|------
          |  Salary  |3500
----------|--------  |------
        |Total Salary|6500



have to create it in sql

and is it possible to get following format in sql

C#
Location  |Department|Salary
----------|----------|-------
   L1     |   D1     |1000
          |   D2     |2000
----------|----------|------
          |  Salary  |3000
----------|----------|-------
   L2     |   D3     |1500
          |   D5     |2000
----------|----------|------
          |  Salary  |3500
----------|--------  |------
        |Total Salary|6500


Thank you
regards
varun vimal
Posted

1 solution

Assuming the mistakes in your data are just typos in the question, Grouping Sets[^] will do what you want.
SQL
WITH cteData As
(
    SELECT
        L.Location,
        D.Department,
        S.Salary
    FROM
        Location As L
        INNER JOIN Department As D
        ON D.ID = L.ID
        INNER JOIN Salary As S
        ON S.ID = L.ID
)
SELECT
    Location,
    CASE
        WHEN Location Is Null THEN 'Total Salary'
        WHEN Department Is Null THEN 'Salary'
        ELSE Department
    END As Department,
    Sum(Salary) As Salary
FROM
    cteData
GROUP BY GROUPING SETS
(
    (Location, Department),
    (Location),
    ()
);

Output:
Location    Department    Salary
L1          D1            1000
L1          D2            2000
L1          Salary        3000
L2          D3            1500
L2          D4            2000
L2          Salary        3500
NULL        Total Salary  6500

Any further formatting needs to be done in the UI.
 
Share this answer
 
Comments
Mathi Mani 27-Jan-16 13:53pm    
It is a 5!!

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