获取上个月 24 日至当月 23 日之间的记录



我对SQL几乎一无所知,我正在尝试在SQL Server Management Studio中进行SQL查询Microsoft其中记录是在动态时间段(24th of last month - 23rd of this month(内接收的。目前,我需要手动编辑日期或通过 excel VBA 宏添加它们,其中两个时间点声明为两个变体。我一直在互联网上寻找,尝试一些事情,例如:

WHERE DATEPART(m,day_id)=DATEPART(m,DATEADD(m,-1,getdate()))
AND DATEPART (yyyy,day_id)=DATEPART(yyyy,DATEADD(m,-1,getdate()))

但这不计入 24-23 日,并给出语法错误。

这是我的代码,我需要手动编辑日期:

SELECT
  reviewer_name,
  CAST(ddd_id AS date) AS day_id,
  report_id,
  report_name,
  amount_events,
  group_name,
  percent_checked_events,
  comment AS SPL_comment
FROM reports_history_GA
WHERE (closed != 1
   AND ddd_id > '2017-01-01'
   AND [percent_checked_events] != '100'
   AND report_name NOT LIKE '%ther_jo%'
   AND report_name NOT LIKE 'QATeam'
   AND comment NOT LIKE '%escal%')
OR    (ddd_id <= '2018-02-23'
   AND check_start_date > '2018-02-23'
   AND comment NOT LIKE '%escal%')
ORDER BY dd_id ASC

这将为您提供日期

select  [24th of last month]    = dateadd(month, datediff(month, 0, getdate()) - 1, 23),
        [23rd of current month] = dateadd(month, datediff(month, 0, getdate()),     22)
SELECT CAST('24 '+ RIGHT(CONVERT(CHAR(11),DATEADD(MONTH,-1,GETDATE()),113),8) AS date) AS LastMonth,
CAST('23 '+ RIGHT(CONVERT(CHAR(11),GETDATE(),113),8) AS date) AS CurrentMonth

输出:

LastMonth   CurrentMonth
2018-02-24  2018-03-23

以下是接受答案的替代方法:

select cast(dateadd(month,-1,dateadd(day,24 - datepart(day,getdate()),getdate())) as date) [24th of previous month],
       cast(dateadd(day,23 - datepart(day,getdate()),getdate()) as date) [23rd of current month]

最新更新