【问题标题】:If there is no data in current month get the last month data如果当前月份没有数据,则获取上个月的数据
【发布时间】:2021-09-01 19:07:37
【问题描述】:

我是 SQL Server 的新手。我有一个查询,它总是返回当月的数据。问题是每个月的第一天,查询必须给我上个月的数据。

因此,如果我在 9 月 3 日运行查询,则查询必须返回 9 月 1 日至 9 月 3 日的数据。但是,如果我在 9 月 1 日运行查询,则必须返回 8 月的所有数据,或者如果我在 10 月 1 日运行,9 月的所有数据等等。

我正在尝试使用WHEREBETWEEN 以及所有这些来解决这个问题。

有什么想法吗?

【问题讨论】:

  • 根据问题指南,请展示您尝试过的内容并告诉我们您发现了什么(在本网站或其他地方)以及为什么它不能满足您的需求。请提供minimal reproducible example 提供样本数据和所需结果。
  • 你应该明白我是新手,而且英语不是我的母语,所以我问或解释事情很复杂。我明白了,很多人只是来这里提出问题而没有任何先前的研究或努力,这不是这个网站的想法,它可能会很烦人。我之前做过一些研究,但我尝试使用的工具非常错误......我会尽力在下一个问题中尽力而为,或者考虑到您的评论,我绝对不会再次尝试提问。

标签: sql sql-server tsql


【解决方案1】:

你可以试试这个。

DECLARE @StartDate DATE 
DECLARE @EndDate DATE

SET @StartDate = DATEADD(MONTH, CASE WHEN DAY(GETDATE()) = 1 THEN -1 ELSE 0 END ,  DATEADD(DAY, - (DAY(GETDATE()) - 1), GETDATE()))
SET @EndDate = CASE WHEN DAY(GETDATE()) = 1 THEN DATEADD(MONTH,1, @StartDate) ELSE GETDATE() END  


SELECT * FROM TheTable WHERE Date BETWEEN @StartDate AND @EndDate

【讨论】:

  • 不过,如果表中的日期存储为 datetime,则不安全。
【解决方案2】:

首先考虑“势在必行”的逻辑。

if todays date is the first of the month then
   the query range is from the first of last month until the the end of last month
else
   the query range is from the start of the current month until today

现在开始将其转换为 TSQL...(无论您的表将日期存储为 date 还是 datetime,这都会起作用)。

-- today
declare @today as date = getdate() -- implicit cast to date will remove time component

--if today's date is the first of the month
if (datepart(day, @today) = 1) 

-- from the first of last month:
>= dateadd(month, -1, @today)

-- until the the end of last month
< @today

-- else from the start of the current month...
>= datefromparts(year(@today), month(@today), 1)

-- until the end of today, which is the same as "before tomorrow"
< dateadd(day, 1, @today)

把它们放在一起!

declare @today date = getdate(); 

declare @startDate date = iif(
   datepart(day, @today) = 1, 
   dateadd(month, -1, @today), 
   datefromparts(year(@today), month(@today), 1)
);

declare @endDate date = iif(
   datepart(day, @today) = 1, 
   @today, 
   dateadd(day, 1, @today)
);

select ... where theDate >= @startDate and theDate < @endDate;

【讨论】:

  • 哇,这是我见过的最好的解释方法之一。我也应该这样解释
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-01
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
相关资源
最近更新 更多