Sql server SQL Server从期间获取操作天数

Sql server SQL Server从期间获取操作天数,sql-server,period,Sql Server,Period,我有桌子: YEAR DATE_FROM DATE_TO 2013 2013-04-21 2013-11-14 2014 2014-04-03 2014-12-03 我需要一个查询,该查询获取@year、@month、@type作为参数,并返回 @类型= 1) 包含在@年的@月期间内的天数 2) 从该期间开始到该年的@月底的天数 示例: @类型=1、@month=5、@year=2013应返回31天 @类型=2、@month=5、@year=2013应返回4

我有桌子:

YEAR    DATE_FROM    DATE_TO

2013    2013-04-21   2013-11-14

2014    2014-04-03   2014-12-03
我需要一个查询,该查询获取@year、@month、@type作为参数,并返回

@类型=

1) 包含在@年的@月期间内的天数

2) 从该期间开始到该年的@月底的天数

示例:

@类型=1、@month=5、@year=2013应返回31天

@类型=2、@month=5、@year=2013应返回40天


先走一步

你需要做两件事。首先是找到匹配的行。第二个是根据需要进行总结。我认为最好的总结方法是将
@年
@月
转换为月初。然后加上一个月,在月底减去一天。我认为以下是逻辑:

  select (case when @type = 1
               then datediff(day, thedate,
                             (case when datediff(day, date_from, dateadd(month, 1, thedate)) > date_to
                                   then dateadd(day, -1, datediff(day, date_from, dateadd(month, 1, thedate)) )
                                   else date_to
                              end) 
                             )
               when @type = 2
               then datediff(day, date_from, dateadd(month, 1, thedate)) - 1
          end)
  from seasons s cross join
       (select cast(cast(@year*100000  + @month*100 + 1 as varchar(255)) as date) as thedate
  where @year * 100 + @month between year(s.date_from) * 100 + month(s.date_from) and
                                     year(s.date_to) * 100 + month(s.date_to)

请使您的示例数据与预期输出同步。你的要求太令人困惑了。条件a和b有相同的输入,但不同的输出。请编辑您的问题以澄清问题!奇怪的是,虽然代码看起来很完美,但最后一行的“')”附近出现了错误的语法