首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对于这个SQL查询,如何根据用户选择的月份和年份,输出28/30/31天的列表?

对于这个SQL查询,如何根据用户选择的月份和年份,输出28/30/31天的列表?
EN

Stack Overflow用户
提问于 2018-01-29 00:57:10
回答 2查看 60关注 0票数 1

我在这里声明了所有的变量。

代码语言:javascript
复制
    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,操作系统是员工ID,Clock_date是时钟输入和时钟输出的一天,我代表时钟输入,O代表时钟输出。

代码语言:javascript
复制
    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

然后,我使用数据透视组合查询,在列中显示数据,如下所示

分支机构编号?时钟日期?员工ID \ IN _ OUT

代码语言:javascript
复制
   PIVOT
  ( min(clock_time)
  FOR clock_type in ([I],[O])
  ) as ThePivot 

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-01-30 03:56:01

代码语言:javascript
复制
Create procedure procname
@year int,
@month int
As
(Rest of the code goes here)

删除年份和月份的声明。

票数 0
EN

Stack Overflow用户

发布于 2018-01-30 01:56:51

创建一个临时表,其中包含所选期间的所有日期,然后对输出表执行左联接,如下所示:

代码语言:javascript
复制
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 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48493013

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档