How can i use PIVOT operator for the following SQL Script to produce the same result?
declare @startdate DATETIME, @enddate DATETIME
declare @site varchar(3)
set @startdate = '2022-03-01'
set @enddate = '2022-03-31'
set @site = '105'
create table #temp_table
(
#site_id varchar(3),
#tran_date varchar(10),
#label_type varchar(20),
#tran_number INT
)
insert into #temp_table
(
#site_id,
#tran_date,
#label_type,
#tran_number
)
(
select rTranslog.Site,
convert(varchar(10),rTranslog.IssueDate,103),
rTranslog.LabelType,
count(*)
from rTranslog
left join rPatients on rTranslog.PatId = rPatients.PatID
left join rConsultant on rTranslog.Consultant = rConsultant.consultant
join rProduct on rProduct.NSVCode = rTranslog.NSVCode
where rTranslog.IssueDate >= @startdate
and rTranslog.IssueDate <= @enddate
and rTranslog.Site = @site
group by rTranslog.Site,
convert(varchar(10),rTranslog.IssueDate,103),
rTranslog.LabelType
)
select #site_id as 'Site',
#tran_date as 'Tran Date',
coalesce(MAX(CASE WHEN #label_type = 'O' THEN #tran_number END),'') AS [OutPatient],
coalesce(MAX(CASE WHEN #label_type = 'I' THEN #tran_number END),'') AS [InPatient],
coalesce(MAX(CASE WHEN #label_type = 'D' THEN #tran_number END),'') AS [Discharge],
coalesce(MAX(CASE WHEN #label_type = 'L' THEN #tran_number END),'') AS [Leave],
coalesce(MAX(CASE WHEN #label_type = 'C' THEN #tran_number END),'') AS [Civas],
coalesce(MAX(CASE WHEN #label_type = 'M' THEN #tran_number END),'') AS [Manufactured],
coalesce(MAX(CASE WHEN #label_type = 'P' THEN #tran_number END),'') AS [Picking Ticket],
coalesce(MAX(CASE WHEN #label_type = 'S' THEN #tran_number END),'') AS [Stock],
coalesce(MAX(CASE WHEN #label_type = 'T' THEN #tran_number END),'') AS [PN],
coalesce(MAX(CASE WHEN #label_type = 'W' THEN #tran_number END),'') AS [Unknown]
from #temp_table
group by #site_id,
#tran_date
drop table #temp_table