SQL日期之间的所有年份和月份

时间:2017-04-12 06:51:42

标签: sql

我有一个小问题,我有一个名为project的表,如下所示:

---------------------------------------
 ProjectId  | StartDate   | EndDate   |
---------------------------------------
     1      | 01/01/2015  | 31/12/2017|

在这些日期之间获得所有月份和年份是否可行:

--------------------
| Month   |   Year  |
--------------------
    1     |   2015  |
    2     |   2015  |
    3     |   2015  |
    4     |   2015  |
    5     |   2015  |
    6     |   2015  |
    7     |   2015  |
    8     |   2015  |
    9     |   2015  |
    10    |   2015  |
    11    |   2015  |
    12    |   2015  |
    1     |   2016  |
    2     |   2016  |
    3     |   2016  |
    4     |   2016  |
    .     |     .   |
    .     |     .   |
    .     |     .   |
    12    |   2017  |

3 个答案:

答案 0 :(得分:1)

如果您的数据库是sql server,则可以运行以下代码来获取结果。

{{1}}

希望它会有所帮助。如果您需要更多帮助,可以查看以下链接 https://blog.sqlauthority.com/2014/12/22/sql-server-list-the-name-of-the-months-between-date-ranges-part-2/

答案 1 :(得分:1)

这是使用PostgreSQL函数generate_seriesextract

的方法
SELECT extract(month FROM date) AS month, extract(year FROM date) AS year
FROM (
    SELECT generate_series('2015-01-01'::date, '2017-12-31'::date, '1 month'::interval) AS date
) AS date_range

您需要修改此项以使用表格中的日期:

SELECT extract(month FROM range) AS month, extract(year FROM range) AS year
FROM (
    SELECT generate_series(StartDate, EndDate, '1 month'::interval) AS range
    FROM project
    WHERE ProjectId = 1
) AS date_range

答案 2 :(得分:0)

在Sql server中,查询您的日期类型

    ;with datecte (date)
AS
 (
    SELECT Convert(date,'01/01/2015',105)
    UNION ALL
    SELECT DATEADD(month,1,date)
    from datecte
    where DATEADD(month,1,date)<= (Select Convert(date,'31/12/2017',105))
)
select month(date),YEAR(date) from datecte