//按月统计,除去周末的考勤,(工时,请假,缺勤)
--建表sql 创建[dbo].[AbsenceHourld]
CREATE TABLE [dbo].[AbsenceHourld](
[id] [int] NULL,
[date] [datetime] NULL,
[name] [varchar](50) NULL,
[hours] [int] NULL
) ON [PRIMARY]
--创建[dbo].[ManHour]
CREATE TABLE [dbo].[ManHour](
[id] [int] NULL,
[date] [datetime] NULL,
[name] [varchar](50) NULL,
[hours] [int] NULL
) ON [PRIMARY]
--建表sql
--统计所有员工-- 按天统计考勤数据
select a.name as 姓名,
CONVERT(varchar(100), a.[date] ,111) as 时间天,
sum(a.[hours])as 工作时间,
sum(isnull(b.[hours],0)) as 请假时间 ,
8-sum(a.[hours])+sum(isnull(b.[hours],0)) as 缺勤时间
from ManHour a
left join AbsenceHourld b
on a.name=b.name
where datepart(weekday, a.[date]) not in (6,7)
group by CONVERT(varchar(100), a.[date] ,111) ,a.name
-- 创建返回某月去掉周末的有效工时天数——函数
alter FUNCTION 返回减周末后月的天数(@date varchar(8))
RETURNS INT
AS
BEGIN
declare @fistM varchar(8) --月的第一天
declare @YY char(4),@MM char(2) --年,月
set @YY=LEFT(@date,4)
set @MM=dateadd(mm,1,@date) --这种截取会让月份是0开头
set @fistM=@YY+@MM+'01'
DECLARE @edate varchar(8),@monthCount INT ,@weekCount int --月的结束时间,月的天数,周末的天数
--取出月的天数 @monthCount
SET @edate =CONVERT(VARCHAR(8), dateadd(D,-1,@fistM),112)
SET @monthCount =CAST(datepart(day,@edate) AS INT)
--月的周末数 @weekCount
set @weekCount=0
declare @wdate varchar(8), @temp_time varchar(8),@WM varchar(6) --周计算(月)第一天,中间变量
set @WM=LEFT(@date,6)
set @wdate=@WM+'01'
set @temp_time=@wdate
while left(@wdate,6)=left(@temp_time,6)
begin
IF DATEPART(WEEKDAY,@temp_time)=1 OR DATEPART(WEEKDAY,@temp_time)=7 --第一天是星期几
set @weekCount=@weekCount+1
set @temp_time=convert(varchar(8),dateadd(D,1,@temp_time),112)
end
return @monthCount-@weekCount
END
select dbo.返回减周末后月的天数('20150105')
--统计所有员工 --月度考勤数据
select a.name as 姓名,
convert(char(4),year(a.[date]))+'年'+convert(char(2),month(a.[date]))+'月' as 时间,
sum(a.[hours])as 工作时间,
sum(isnull(b.[hours],0)) as 请假时间,
8*dbo.返回减周末后月的天数(CONVERT(varchar(12),min(a.[date]), 112 )) --调用函数取得
-sum(a.[hours])+sum(isnull(b.[hours],0)) as 缺勤时间
from ManHour a
left join AbsenceHourld b
on a.name=b.name
where datepart(weekday, a.[date]) not in (6,7)
group by month(a.[date]),a.name,year(a.[date])