我有时间间隔,我希望我的查询输出一个列Days
的表,该列将以自然顺序在该时间间隔内包含所有星期几,所以如果间隔大于一周(即'2014-2-1'和'2014-2-21'之间),结果将是:
Day
----
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
如果间隔开始,让我们说星期五,并在下一个星期一结束(即'2014-2-21'和'2014-2-24'之间),输出将是:
Day
----
Sunday
Monday
Friday
Saturday
答案 0 :(得分:2)
我会使用以下方法:
SQL:
DECLARE @StartDate DATE = '20140221'
, @EndDate DATE = '20140224'
SELECT
datename(weekday, v1.day) as weekday,
(((@@datefirst-1) + datepart(weekday, v1.day)) % 7) as weekday_num,
v1.day FROM (
SELECT DATEADD(DAY, nbr - 1, @StartDate) AS day
FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY c.object_id ) AS Nbr
FROM sys.columns c
) nbrs
WHERE nbr - 1 <= DATEDIFF(DAY, @StartDate, @EndDate)
) v1
order by 2
UPDATE
要正确处理超过7天的案例,您可以使用SELECT
将其打包在另一个DISTINCT
中:
DECLARE @StartDate DATE = '20140221'
, @EndDate DATE = '20140224'
SELECT DISTINCT weekday, weekday_num FROM (
SELECT
datename(weekday, v1.day) as weekday,
(((@@datefirst-1) + datepart(weekday, v1.day)) % 7) as weekday_num,
v1.day FROM (
SELECT DATEADD(DAY, nbr - 1, @StartDate) AS day
FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY c.object_id ) AS Nbr
FROM sys.columns c
) nbrs
WHERE nbr - 1 <= DATEDIFF(DAY, @StartDate, @EndDate)
) v1
) v2 order by 2
答案 1 :(得分:0)
您可以使用DatePart和DateName的组合来执行此操作。你可以这样得到你的日期:
select datename(dw,getdate()) --Friday
select datepart(dw,getdate()) --6
只需用您的字段名称替换 getdate()(将返回今天的日期)。然后,您可以显示DateName,但按DatePart排序。