简体   繁体   English

动态声明当前月份的开始/结束日期

[英]Dynamically Declare Start/End Dates From Current Month

I have a pretty basic query that I run monthly. 我有一个非常基本的查询,每月运行一次。 Every month I have to manually change the query to fit the current month start and end date. 每个月我都必须手动更改查询以适合当前月份的开始和结束日期。 I've tried using some of the examples from previous answers but can't seem the make it work. 我尝试使用以前答案中的一些示例,但似乎无法使其正常工作。 Notably because I am trying to include the entire last day of the month, as shown by my 23:59:59 parameter. 值得注意的是,因为我试图包括该月的最后一天,如我的23:59:59参数所示。 What is the best way to accomplish this? 做到这一点的最佳方法是什么?

SELECT *
FROM WorkOrder
where active = 1 and
WorkOrderStatusId in (6,8) AND
dateCreated >= '5/1/2017' and
dateCreated <= '5/31/2017 23:59:59'

what you can actually do is get the month and year 您实际可以做的是获取月份和年份

SELECT *
FROM WorkOrder
where active = 1 and
WorkOrderStatusId in (6,8) AND
year(dateCreated) = 2017
month(dateCreated) = 5  

Three things: 三件事:

First: dates look like 2017-05-01 not 5/1/2017 in most DBMS representations. 首先:在大多数DBMS表示中,日期看起来像2017-05-01而不是5/1/2017年5月1日。

Second: you want this sort of expression (note the < ) to make sure you get all rows. 第二:您想要这种类型的表达式(请注意< )以确保获得所有行。 That's a better approach than the 23:59:59 stuff. 这比23:59:59方法更好。

where  dateCreated >= '2017-05-01'
  and  dateCreated <  '2017-06-01'

Third, you probably want a way of saying 第三,您可能想要一种表达方式

 where dateCreated >= first_day_of_last_month
   and dateCreated <  first_day_of_this_month

in a way where you don't have to change the query every month. 您不必每个月都更改查询。

This works differently in different makes and models of database server. 在不同品牌和型号的数据库服务器中,此方法的工作方式有所不同。 You didn't tell us which one you're using, so... 您没有告诉我们您使用的是哪一个,所以...

In MS SQL Server, DATEADD(DAY, 1-DATEPART(DAY, GETDATE()), GETDATE()) gives you the first of the present month, so 在MS SQL Server中, DATEADD(DAY, 1-DATEPART(DAY, GETDATE()), GETDATE())给您本月的第一天,因此

where dateCreate >= 
         DATEADD(MONTH, -1, DATEADD(DAY, 1-DATEPART(DAY, GETDATE()), GETDATE()))
  and dateCreate < 
         DATEADD(DAY, 1-DATEPART(DAY, GETDATE()), GETDATE())

In MySQL DATE_FORMAT(CURDATE(), '%Y-%m-01') gives you midnight on the first day of the present month, so this where clause gets last month's rows. 在MySQL DATE_FORMAT(CURDATE(), '%Y-%m-01')在当月第一天的午夜给您,因此此where子句获取上个月的行。

where dateCreated >= DATE_FORMAT(CURDATE(), '%Y-%m-01') - INTERVAL 1 MONTH
  and dateCreated <  DATE_FORMAT(CURDATE(), '%Y-%m-01')

In Oracle (cue if I were a rich man from Fiddler on the Roof ) TRUNC(SYSDATE, 'MM') gives you the first of the month, so this gets last month's rows. 在Oracle中(提示一下,如果我是 屋顶上的Fiddler 的有钱人TRUNC(SYSDATE, 'MM')给您本月的第一天,因此得到上个月的行。

where dateCreate >= ADD_MONTHS(-1, TRUNC(SYSDATE, 'MM'))
  and dateCreate <  TRUNC(SYSDATE, 'MM')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM