如何在通用查询中获取当前周,目前我可以获得日期范围,但我希望以动态方式获得当前周。
这就是我所拥有的:
WITH mycte AS
(
SELECT CAST('2011-01-01' AS DATETIME) DateValue
UNION ALL
SELECT DateValue + 1
FROM mycte
WHERE DateValue + 1 < '2021-12-31'
)
SELECT DateValue
FROM mycte
OPTION (MAXRECURSION 0)
根据今天的日期,我希望得到类似的内容:
11-04-2013 11-05-2013 11-06-2013 11-07-2013 11-08-2013 11-09-2013 11-10-2013
答案 0 :(得分:1)
在SQL Server中执行此操作的一种方法
WITH weekdays AS
(
SELECT 0 day
UNION ALL
SELECT day + 1 FROM weekdays WHERE day < 6
)
SELECT DATEADD(DAY, day, DATEADD(DAY, 2-DATEPART(WEEKDAY, CONVERT (date, GETDATE())), CONVERT (date, GETDATE()))) date
FROM weekdays
输出:
| DATE | |------------| | 2013-11-04 | | 2013-11-05 | | 2013-11-06 | | 2013-11-07 | | 2013-11-08 | | 2013-11-09 | | 2013-11-10 |
这是 SQLFiddle 演示
在MySQL中
SELECT CURDATE() + INTERVAL 1 - DAYOFWEEK(CURDATE()) DAY + INTERVAL day DAY date
FROM
(
SELECT 1 day UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4 UNION ALL
SELECT 5 UNION ALL
SELECT 6 UNION ALL
SELECT 7
) w
这是 SQLFiddle 演示