参加PIVOT

时间:2019-01-16 05:09:37

标签: sql sql-server

我有一个出勤表,结果如下图所示

enter image description here

我需要以以下格式获取结果:

enter image description here

下面是我使用的示例PIVOT查询。请帮助我进行查询以获得所需的结果。

CREATE TABLE #Temp
(
[empcode] varchar(15),
[empDesc] nvarchar(300),
[hrlog_Date] date,
[hrlog_in] datetime,
[hrlog_Out] datetime,
[hrlog_Latein] datetime,
[hrlog_EarlyOut] datetime,
)
DECLARE @Start datetime,@End datetime,@DList varchar(2000),@Sql varchar(max),@Sql1 varchar(max);
SET @Start=@StartDate;
SET @End=@EndDate;
INSERT INTO #Temp

Select h.emp_code,e.emp_desc as emp_Desc,h.hrlog_Date, CONVERT(datetime,h.hrlog_in, 105) as hrlog_in
,CONVERT(datetime,h.hrlog_out,105) as hrlog_out
,
case when cast(h.hrlog_in as time)> cast('8:45' as time) then 
cast(h.hrlog_Date as NVARCHAR(50))+' ' +CAST(DATEDIFF(second, cast('8:45' as time), cast(h.hrlog_in as time) ) / 60 / 60 % 24  AS NVARCHAR(50))+ ':'    + 
CAST(DATEDIFF(second,cast('8:45' as time),  cast(h.hrlog_in as time) ) / 60 % 60 AS NVARCHAR(50)) 
else cast(h.hrlog_Date as nvarchar(50)) +' 0:00' end
mrngLate
,case when cast(h.hrlog_out as time) < cast('17:15' as time)  then 
cast(h.hrlog_Date as NVARCHAR(50))+' ' +CAST(DATEDIFF(second, cast(h.hrlog_out as time), cast('17:15' as time) ) / 60 / 60 % 24  AS NVARCHAR(50))+ ':'    + 
CAST(DATEDIFF(second,  cast(h.hrlog_out as time),cast('17:15' as time) ) / 60 % 60 AS NVARCHAR(50))
else cast(h.hrlog_Date as nvarchar(50)) +' 0:00'  end EvenEarly

from HRDailyLog h INNER JOIN FTEmployee e ON h.emp_code=e.Emp_Code  
LEFT OUTER JOIN sys_CostCenterDep c ON e.sys_ccdepcode = c.sys_ccDepCode
LEFT OUTER JOIN FTJobDesc j ON e.job_code = j.Job_code
LEFT OUTER JOIN sysDep d ON j.sys_depcode = d.Sys_Depcode
LEFT OUTER JOIN HrShift s ON e.SFT_Code = s.SFT_Code
Where (h.hrlog_date between  @Start and @End and e.SFT_Code is not null)  
and CASE WHEN @sftCode = '-1' then @sftCode else e.SFT_Code end= @sftCode
and CASE WHEN @depCode = '-1' then @depCode else d.Sys_Depcode end= @depCode
and h.sys_bRcode = @brCode
SELECT DATEADD(dd,number,@Start) AS Date INTO #Date
FROM master..spt_values
WHERE type='p'
AND DATEADD(dd,number,@Start)<=@End
SELECT @DList=LEFT(dl.Dates,LEN(dl.Dates)-1)
FROM
(SELECT CAST(Date as varchar(11)) + ','
 FROM #Date
 FOR XML PATH('')   
)dl(Dates)
SET @Sql='SELECT * FROM (
SELECT d.Date as dateIn ,t.empcode as empcode,t.empDesc as empDesc,(CONVERT(nvarchar(5),t.hrlog_in, 108)+'' to ''+CONVERT(nvarchar(5),t.hrlog_Out, 108)) as hrlog_in
 FROM #Date d
LEFT JOIN #Temp t
ON   CONVERT(nvarchar(10),  t.hrlog_in, 111)=d.Date
)tm
PIVOT (MIN(hrlog_in) FOR dateIn IN ([' +  REPLACE(@DList,',','],[')+ ']))p
WHERE empcode IS NOT NULL' 
EXEC(@Sql)

0 个答案:

没有答案