本帖最后由 hessen 于 2023-4-22 11:22 编辑
列出一段时间或指定时间段之间的日期或年月或数字序列
要取得给定的两个数字之间的序列,或者给定的两个日期之间的日期、年月等可以按下面的方法实现:
1、创建表值函数
执行下面的语句在数据库中创建表值函数。
- IF OBJECT_ID('dbo.GetNums','IF') IS NOT NULL
- DROP FUNCTION dbo.GetNums;
- GO
- CREATE FUNCTION dbo.GetNums(@low AS BIGINT, @high AS BIGINT) RETURNS TABLE
- AS
- RETURN
- WITH
- L0 AS (SELECT c FROM (VALUES(1),(1)) AS D(c)),
- L1 AS (SELECT 1 AS c FROM L0 AS A CROSS JOIN L0 AS B),
- L2 AS (SELECT 1 AS c FROM L1 AS A CROSS JOIN L1 AS B),
- L3 AS (SELECT 1 AS c FROM L2 AS A CROSS JOIN L2 AS B),
- L4 AS (SELECT 1 AS c FROM L3 AS A CROSS JOIN L3 AS B),
- L5 AS (SELECT 1 AS c FROM L4 AS A CROSS JOIN L4 AS B),
- Nums AS (SELECT ROW_NUMBER() OVER(ORDER BY(SELECT NULL)) AS rownum
- FROM L5)
- SELECT TOP(@high - @low + 1) @low + rownum - 1 AS n
- FROM Nums
- ORDER BY rownum;
- GO
复制代码
下面分别是取得数字序列或日期序列的查询写法,比较简单,请回复后查看。
2、取的数字序列
比如要取得1到100之间的自然数序列,可以如下查询
3、取得日期序列
比如要得到2023年1月1日到2023年4月22日之间的日期序列,可以按如下查询
4、取得指定日期之间的年月
比如:要取得2023年1月到2023年4月之间的月份
|
hessen