每月的第一天

时间:2018-04-06 08:42:56

标签: sql

select  distinct
  DATEPART("yyyy", datum) AS year
, DATEPART("mm", datum)   AS month 
=

任何人都可以告诉我如何获得本月的第一天。如果我尝试“Datepart(”dd“,datum)作为”日“,我每天都会得到而不仅仅是第一天

4 个答案:

答案 0 :(得分:2)

对于SQL Server 2012+,请尝试:

DATEFROMPARTS(YEAR(datum), MONTH(datum), 1)

答案 1 :(得分:0)

CREATE TABLE Table1
    ([datum] date)
;

INSERT INTO Table1
    (datum)
VALUES
    ('04-06-2018')
;

SELECT distinct DATEPART("yyyy", datum) AS year
  ,DATEPART("mm", datum)   AS month 
  ,DATENAME(dw,CAST(DATEPART("mm", datum) AS VARCHAR) 
   + '/' 
   + CAST('01' AS VARCHAR) 
   + '/' 
   + CAST(DATEPART("yyyy", datum) AS VARCHAR))  AS [First day of month]
FROM table1
order by year, month

输出

year    month   First day of month
2018    4       Sunday

现场演示

  

http://sqlfiddle.com/#!18/69402/4

答案 2 :(得分:0)

您可以在上个月使用月末函数(EOMONTH()),并添加1天。

DECLARE @Date DATE = '2018-06-08'

SELECT
    OriginalDate = @Date,
    EndOfPreviousMonth = EOMONTH(@Date, -1),
    StartOfMonth = DATEADD(DAY, 1, EOMONTH(@Date, -1))

答案 3 :(得分:0)

每月的第一天总是第一天。

select  distinct
  DATEPART("yyyy", datum) AS year, 
  DATEPART("mm", datum)   AS month, 
  1  AS FirstDayOfMonth
from qdatum
order by year, month

(我对你想要实现的目标毫无头绪)