Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get a sql query in a pivot format?

I am trying to get a simple join query results in a pivot format.

Sharing the sample query:

if object_id('tempdb.dbo.#t') is not null      
    drop table #t    

create table #t (
    EmpName nvarchar(1000),
    CaseNumber nvarchar(1000),
    [WeekDay]   nvarchar(1000)
)

insert into #t values ('Sam','SM100','Monday')
insert into #t values ('Sam','SM100','Wednesday')
insert into #t values ('Sam','SM100','Thursday')
insert into #t values ('Peter','PT200','Monday')
insert into #t values ('Peter','PT200','Tuesday')
insert into #t values ('Peter','PT200','Wednesday')
insert into #t values ('Peter','PT200','Thursday')
insert into #t values ('Peter','PT200','Friday')
insert into #t values ('Peter','PT200','Saturday')
insert into #t values ('Peter','PT200','Sunday')

select * from #t

-- Expected output tabular format

From John's query...

;with cte as
(
Select * 
 From (Select *,Val=1 From #t) src
 Pivot (sum(Val) for weekday in ([Sunday],[Monday],[Tuesday],[Wednesday],[Thursday],[Friday],[Saturday]) )pvt
 )
 select EmpName, CaseNumber, 
 Case When Sunday = 1 then 'Yes' when isnull(Sunday,'') = '' then 'No' end Sunday,
 Case When Monday = 1 then 'Yes' when isnull(Monday,'') = '' then 'No' end Monday,
 Case When Tuesday = 1 then 'Yes' when isnull(Tuesday,'') = '' then 'No' end Tuesday,
 Case When Wednesday = 1 then 'Yes' when isnull(Wednesday,'') = '' then 'No' end Wednesday,
 Case When Thursday = 1 then 'Yes' when isnull(Thursday,'') = '' then 'No' end Thursday,
 Case When Friday = 1 then 'Yes' when isnull(Friday,'') = '' then 'No' end Friday,
 Case When Saturday = 1 then 'Yes' when isnull(Saturday,'') = '' then 'No' end Saturday 
  from cte

I prefer not to use too many case statements...

like image 582
goofyui Avatar asked Mar 05 '23 06:03

goofyui


1 Answers

You can use conditional aggregation:

SELECT
    EmpName,
    MAX(CASE WHEN WeekDay = 'Sunday'    THEN CaseNumber END) AS Sunday,
    MAX(CASE WHEN WeekDay = 'Monday'    THEN CaseNumber END) AS Monday,
    MAX(CASE WHEN WeekDay = 'Tuesday'   THEN CaseNumber END) AS Tuesday,
    MAX(CASE WHEN WeekDay = 'Wednesday' THEN CaseNumber END) AS Wednesday,
    MAX(CASE WHEN WeekDay = 'Thursday'  THEN CaseNumber END) AS Thursday,
    MAX(CASE WHEN WeekDay = 'Friday'    THEN CaseNumber END) AS Friday,
    MAX(CASE WHEN WeekDay = 'Saturday'  THEN CaseNumber END) AS Saturday
FROM #t 
GROUP BY EmpName

Demo on DB Fiddle with your sample data:

EmpName | Sunday | Monday | Tuesday | Wednesday | Thursday | Friday | Saturday
:------ | :----- | :----- | :------ | :-------- | :------- | :----- | :-------
Peter   | PT200  | PT200  | PT200   | PT200     | PT200    | PT200  | PT200   
Sam     | null   | SM100  | null    | SM100     | SM100    | null   | null    
like image 162
GMB Avatar answered Mar 07 '23 09:03

GMB