如何在sql查询中执行计算

时间:2014-03-07 10:37:09

标签: sql sql-server

我的要求是计算一个月内的付款日。这是完成付款日= NoOfDaysInMonth-LEAVES。

为了获得我正在使用的日子

 declare @DATE datetime
 declare @NoOfDaysInMonth int
 set @DATE='2014-3-01'

 select @NoOfDaysInMonth= DAY(DATEADD(DD,-1,DATEADD(MM,DATEDIFF(MM,-1,@DATE),0)))
 print @NoOfDaysInMonth

这将返回31天。

以下是我以前的查询无效。

  *******  datediff(day, MONTH(getdate()), dateadd(month, 1, month(getdate())))-(SELECT TOTALUNPAIDLEAVES FROM  FN_GETTOTALLEAVESFORANEMPLOYEE(VW_EMPLOYEE_DETAILS.EMPLOYEEID,'''+@YEAR+''','''+@MONTH+''')) as [Paid Days] FROM  VW_EMPLOYEE_DETAILS'

取代

 datediff(day, MONTH(getdate()), dateadd(month, 1, month(getdate()))) 

我需要传递变量@NoOfDaysInMonth。

 @NoOfDaysInMonth-(SELECT TOTALUNPAIDLEAVES FROM  FN_GETTOTALLEAVESFORANEMPLOYEE(VW_EMPLOYEE_DETAILS.EMPLOYEEID,'''+@YEAR+''','''+@MONTH+''')) as [Paid Days] FROM  VW_EMPLOYEE_DETAILS

修改我的代码后

SET @COMMANDS=@COMMANDS+' (SELECT TOTALLEAVESUSED FROM FN_GETTOTALLEAVESFORANEMPLOYEE(VW_EMPLOYEE_DETAILS.EMPLOYEEID,'''+@YEAR+''','''+@MONTH+''')) as [Total Leaves Used],(SELECT TOTALUNPAIDLEAVES FROM FN_GETTOTALLEAVESFORANEMPLOYEE(VW_EMPLOYEE_DETAILS.EMPLOYEEID,'''+@YEAR+''','''+@MONTH+''')) as [Total UnPaid  Leaves], ( select @DaysInMonth -(SELECT TOTALUNPAIDLEAVES FROM FN_GETTOTALLEAVESFORANEMPLOYEE(VW_EMPLOYEE_DETAILS.EMPLOYEEID,'''+@YEAR+''','''+@MONTH+'''))) as [Paid Days] FROM  VW_EMPLOYEE_DETAILS' 

1 个答案:

答案 0 :(得分:1)

你的计算没问题。最后一个陈述应该是:

select @NoOfDaysInMonth-(SELECT TOTALUNPAIDLEAVES FROM ...) as Result

请记住将其作为批处理执行(此语句与先前的代码一起作为一组语句执行)。否则,变量@NoOfDaysInMonth将丢失。