Sql 从日期范围中获取特定日期
如何从日期范围中获得一天Sql 从日期范围中获取特定日期,sql,sql-server,sql-server-2008,Sql,Sql Server,Sql Server 2008,如何从日期范围中获得一天 例如:-如果假设我的日期范围为2014年6月22日至2014年6月28日,那么我希望得到该日期范围的星期一,即2014年6月23日为星期一好的,我得到了一个适合我的日期范围 Select date from table where date between range1 and range2 and datename(mm,date) = 'Monday' declare @DateFrom DateTime = CONVERT(DATETIME, '22
例如:-如果假设我的日期范围为2014年6月22日至2014年6月28日,那么我希望得到该日期范围的星期一,即2014年6月23日为星期一好的,我得到了一个适合我的日期范围
Select date
from table
where date between range1 and range2
and datename(mm,date) = 'Monday'
declare @DateFrom DateTime = CONVERT(DATETIME, '22/06/2014', 103)
declare @DateTo DateTime = CONVERT(DATETIME, '28/06/2014', 103)
;WITH CTE(dt)
AS
(
Select @DateFrom
Union All
Select DATEADD(d,1,dt)FROM CTE
Where dt<@DateTo
)
select *,'Monday' as [Day] from cte where datename(dw,dt) = 'Monday'
只需将它放在cte select*from cte之后,其中datenamedw,dt='Monday'。另外,我认为如果你必须一直这样做计算,这是值得注意的。您可能需要考虑建立日历表。您可以在其中保存星期几、季度等内容@JChao:-感谢您对其进行优化。!
declare @DateFrom DateTime = CONVERT(DATETIME, '22/06/2014', 103)
declare @DateTo DateTime = CONVERT(DATETIME, '28/06/2014', 103)
;WITH CTE(dt)
AS
(
Select @DateFrom
Union All
Select DATEADD(d,1,dt)FROM CTE
Where dt<@DateTo
)
select *,'Monday' as [Day] from cte where datename(dw,dt) = 'Monday'