使用SQL中的CTE创建表

时间:2018-11-16 23:37:41

标签: sql-server-2008

我有一个查询,哪里可以在CTE中使用create table?由于我无法在数据库中创建任何新表。我正在尝试计算工作日和经过的工作日数(不包括节假日和周末)。但是此创建表不起作用。如果有什么办法可以做到?由于有了这个创建表,我没有得到任何结果。

create table holidays(holiday date)
insert holidays values ('11-22-2018'),('11-23-2018')

;with dates as(
    select dateadd(d,-day(getdate())+1,convert(date,getdate())) as startofmonth,
    dateadd(d,-1,dateadd(m,1,dateadd(d,-day(getdate())+1,convert(date,getdate())))) as endofmonth,
    convert(date,getdate()) as today
)
,holidaycount as (
    select count(*) as holidaysinmonth,
        sum(case when holiday<=today then 1 else 0 end) as holidaystodate
    from dates
    join holidays on holiday between startofmonth and endofmonth
)
,daycounts as(
    select dates.*,

       (DATEDIFF(dd, startofmonth, endofmonth) + 1)
      -(DATEDIFF(wk, startofmonth, endofmonth) * 2)
      -(CASE WHEN DATENAME(dw, startofmonth) = 'Sunday' THEN 1 ELSE 0 END) 
      -(CASE WHEN DATENAME(dw, endofmonth) = 'Saturday' THEN 1 ELSE 0 END)
      -isnull(holidaysinmonth,0) as wkdaysinmonth,

       (DATEDIFF(dd, startofmonth, today) + 1)
      -(DATEDIFF(wk, startofmonth, today) * 2)
      -(CASE WHEN DATENAME(dw, startofmonth) = 'Sunday' THEN 1 ELSE 0 END) 
      -(CASE WHEN DATENAME(dw, today) = 'Saturday' THEN 1 ELSE 0 END)
      -isnull(holidaystodate,0) as wkdaystodate

    from dates
    cross join holidaycount
) 

select * from daycounts 

谢谢。

1 个答案:

答案 0 :(得分:0)

使用表变量:

declare @holidays table (holiday date)
insert @holidays values ('11-22-2018'),('11-23-2018')

;with dates as(
    select dateadd(d,-day(getdate())+1,convert(date,getdate())) as startofmonth,
    dateadd(d,-1,dateadd(m,1,dateadd(d,-day(getdate())+1,convert(date,getdate())))) as endofmonth,
    convert(date,getdate()) as today
)
,holidaycount as (
    select count(*) as holidaysinmonth,
        sum(case when holiday<=today then 1 else 0 end) as holidaystodate
    from dates
    join @holidays on holiday between startofmonth and endofmonth
)

使用cte:

;with dates as(
    select dateadd(d,-day(getdate())+1,convert(date,getdate())) as startofmonth,
    dateadd(d,-1,dateadd(m,1,dateadd(d,-day(getdate())+1,convert(date,getdate())))) as endofmonth,
    convert(date,getdate()) as today
), holidays as (
    select holiday
    from (values ('11-22-2018'),('11-23-2018') ) x (holiday)
 )
,holidaycount as (
    select count(*) as holidaysinmonth,
        sum(case when holiday<=today then 1 else 0 end) as holidaystodate
    from dates
    join holidays on holiday between startofmonth and endofmonth
)

小心日期文字,您假设数据库将dd-mm-yyyy字符串作为日期。可能并非总是如此,因此,请使用SQL Server将理解为日期的YYYYMMDD,或者最好的方式是YYYY-MM-DD。