using Pivot in SQL Query

2019-09-11 06:17发布

I have the following table structure also I have mention my expected output please help me with query As per My previous question

Get count for multiple fields using group by in SQL

i am getting output as follows using below query

select data.category, cl.combovalue as esilocation, cd.combovalue as esidispensary,
    year(date) as year, month(date) as month,
    sum(data.joins) as [Joining Count], sum(data.terms) as [Termination Count]
from (
    select category, esilocation, esidispensary, dateofjoining as date,
           1 as joins, 0 as terms
    from dbo.employeedetail
    where dateofjoining is not null
    union all
    select category, esilocation, esidispensary, terminationdate as date,
           0 as joins, 1 as terms
    from dbo.employeedetail
    where terminationdate is not null
) data
left join dbo.combovalues cl on cl.id = data.esilocation
left join dbo.combovalues cd on cd.id = data.esidispensary
where category in ( 1, 2 ) 
and date >= '2014-01-01' 
and date <= '2014-12-31'
group by data.category, cl.combovalue, cd.combovalue, year(date), month(date)

Query output :

category    esilocation esidispensary   year    month   Joining Count   Termination Count
1                mumbai     mumbai       2014    8          1             0
1                mumbai     mumbai       2014    11         0             1
1                pune       mumbai       2014    6          1             0
1                pune       mumbai       2014    8          1             1
2                pune       mumbai       2014    10         1             0
2                pune       mumbai       2014    11         0             1
2                pune       pune         2014    9          2             0
2                pune       pune         2014    11         0             2

But problem is i want Pivot of this above table i.e

Expected Output

 category   esilocation esidispensary   8/2014 join   8/2014 term   11/2014 join   11/2014 term    
   1        mumbai        mumbai             1             0            0             1
   1        pune          mumbai             1             1            null          null
   2        pune          mumbai            null           null         0             1
   2        pune          pune              null           null         0             2

0条回答
登录 后发表回答