简体   繁体   中英

Regarding this SQL query, how can I output list of 28/30/31 days according to user's choice of certain month and year

I've declared all the variables right here.

    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))

This is the body of the query, I want to output Branch_No,operid is Staff ID, Clock_date is the day of the clock In and clock Out , [I] stands for clock in , [O] stands for clock Out.

    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

Then, I use Pivot to combine the query to show the data in column like this

Branch Number |Clock Date | Staff ID | IN | OUT

   PIVOT
  ( min(clock_time)
  FOR clock_type in ([I],[O])
  ) as ThePivot 

The Table

Create a temporary table that contains all the dates for the selected period, then do a left join on your output table, like the following:

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 
Create procedure procname
@year int,
@month int
As
(Rest of the code goes here)

Remove the declaration of year and month.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM