并提前感谢你。我远不是一个sql开发人员,但有一些经验,我觉得这应该是相当简单的。
我发现下面的查询返回了该月的剩余天数。它就像一个魅力。但是当我尝试将它附加到一个简单的select语句中从表中获取数据时,我无法将其作为列追加。任何帮助将非常感激。
Declare @DaysLeft as INT
;With MyCTE AS
(
SELECT number + 1 as 'CurrentDay'
FROM master..spt_values
WHERE type='p'
AND number < datepart(dd, DateAdd(day,-1,DateAdd(Month,1,DateAdd(Month,
DateDiff(Month, 0, GETDATE()),0))))
AND datename(WEEKDAY,DateAdd(Month, DateDiff(Month, 0, GETDATE()),
number) ) not in ('Saturday','Sunday')
)
Select @DaysLeft = (Select COUNT(*) As MyTotal from MyCTE
WHERE CurrentDay >= DATEPART(DD, GETDATE()))
Select @DaysLeft as 'Remaining'
我在尝试什么:
Select column 1, column 2 , Remaining (code from above) from TableName
答案 0 :(得分:0)
我认为这是获得本月剩余天数的简单方法:
with remainingDays as (
select dateadd(day, 1, currdate) as dte
from (select cast(getdate() as date) currdate) x
where month(dateadd(day, 1, currdate)) = month(getdate())
union all
select dateadd(day, 1, dte) as dte
from remainingDays
where month(dateadd(day, 1, dte)) = month(getdate())
)
select *
from remainingDays;
它使用递归CTE,但这种类型的操作不应该有那么多开销。
Here它在Rex Tester中。
答案 1 :(得分:0)
谢谢你的工作。非常感激。这是我的最终查询:
Declare @DaysLeft as INT
;With MyCTE AS
(
SELECT number + 1 as 'CurrentDay'
FROM master..spt_values
WHERE type='p'
AND number < datepart(dd, DateAdd(day,-1,DateAdd(Month,1,DateAdd(Month,
DateDiff(Month, 0, GETDATE()),0))))
AND datename(WEEKDAY,DateAdd(Month, DateDiff(Month, 0, GETDATE()),
number) ) not in ('Saturday','Sunday')
)
Select @DaysLeft = (Select COUNT(*) As MyTotal from MyCTE
WHERE CurrentDay >= DATEPART(DD, GETDATE()))
SELECT column 1, column 2, @daysLeft 'remaining'
FROM TableName