我已经在这里声明了所有变量。
declare @FromDate as datetime;
declare @ToDate as datetime;
declare @OperID as varchar(20) = 'OP1';
declare @Year as int = 2018
declare @Month as int = 1
set @FromDate = convert(date,convert(varchar,@Year) + '-' +
convert(varchar,@Month) + '-01')
set @ToDate = dateadd(d,-1,DATEADD(m, 1, @FromDate))
这是查询的主体,我想输出Branch_No,operid是员工ID,Clock_date是时钟输入和时钟输出的日期,[I]代表时钟输入, [O]代表时钟输出。
select Branch_no, operid, clock_date, [I], [O]
from
( select Branch_no, operid,
convert(date, clock_date) as clock_date,
convert(time, clock_date) as clock_time,
clock_type, Workstation_no
from ROSTER_TIMECLOCK
where Clock_date >=CONVERT(DATETIME, @FromDate, 102)
and Clock_date <=CONVERT(DATETIME, @ToDate, 102)
and OperID=@OperID ) as TheClock
然后,我使用Pivot组合查询以显示列中的数据,如此
分行编号|时钟日期|员工ID | IN | OUT
PIVOT
( min(clock_time)
FOR clock_type in ([I],[O])
) as ThePivot
答案 0 :(得分:0)
创建一个临时表,其中包含所选时段的所有日期,然后在输出表上执行左连接,如下所示:
Create procedure nameofsp
@year int,
@month int
As
declare @FromDate as datetime
declare @ToDate datetime
declare @OperID varchar( 20 )
set @FromDate = convert(datetime,convert(varchar,@Year) + '-' +
convert(varchar,@Month) + '-01')
set @ToDate = dateadd(d,-1,DATEADD(m, 1, @FromDate))
-- create a table that contains all the dates for the period selected
declare @dates table( currentdate datetime )
;with cte( curr )
as
(
select @fromdate
union all
select dateadd( d, 1, curr )
from cte
where curr < @todate
)
insert into @dates( currentdate )
select curr
from cte
select a.CurrentDate,
b.operId,
b.Branch_No,
b.I,
b.O
from @dates a
left outer join @inout b on b.clock_date = a.currentdate
order by a.currentdate, b.i
答案 1 :(得分:0)
Create procedure procname
@year int,
@month int
As
(Rest of the code goes here)
删除年份和月份的声明。