0

我正在尝试获取某个日期范围内的工作日数并将其分配给一个变量,但我似乎无法获得它。我只尝试了我的子查询,它可以很好地让我得到不同的日期,但我需要对它们进行计数。这是我希望工作的代码:

 declare @end date='2016/05/06' 
 declare @begin date = DATEADD(month, DATEDIFF(month, 0, @end), 0) 
 declare @begin31 date = DATEADD(MONTH, -1, @end)

 declare @tmprocdays int

  @tmprocdays = select count(*) from (select distinct WORKDATE from Daily where WORKDATE between @begin and @end)    <<<-----  NOT WORKING

该错误表明问题在 ) 附近,我尝试将 while 放在括号中,但这也不起作用。

4

3 回答 3

1

试试这个

declare @end date='2016/05/06' 
 declare @begin date = DATEADD(month, DATEDIFF(month, 0, @end), 0) 
 declare @begin31 date = DATEADD(MONTH, -1, @end)

 declare @tmprocdays int

 set  @tmprocdays = select count(*) from (select distinct WORKDATE from Daily where WORKDATE between @begin and @end) a   <<<-----  NOT WORKING

将上面的最后两行替换为:

select @tmprocdays = count(*) 
from 
(
  select distinct WORKDATE from Daily where WORKDATE between @begin and @end
) a  

或者甚至更好

  select  @tmprocdays = count(distinct WORKDATE) from Daily where WORKDATE between @begin and @end
于 2016-07-19T23:49:13.413 回答
1

主要问题是子查询周围缺少括号。

以下是对代码的一些修复:

declare @end date = '2016-05-06';
declare @begin date = DATEADD(month, DATEDIFF(month, 0, @end), 0);
declare @begin31 date = DATEADD(MONTH, -1, @end);

declare @tmprocdays int;

select @tmprocdays = count(distinct WORKDATE)
from Daily
where WORKDATE between @begin and @end ; 

变化:

  • 将 放入@tmprocdays =语句select本身。您的子查询缺少括号。
  • 在每行末尾添加分号。
  • Removed the subquery, using count(distinct) instead.
  • Changed the date to YYYY-MM-DD format. This is at least an ISO standard.

The last three are cosmetic.

于 2016-07-19T23:51:01.330 回答
1

The from clause must always contain either a table name, or in the case of a subquery it must be aliased:

If you add any identifier (word of letter) after your subquery it will work fine, eg:

@tmprocdays = select count(*) from (select distinct WORKDATE from Daily where WORKDATE between @begin and @end) xxx
于 2016-07-19T23:51:21.893 回答