简体   繁体   English

获取上个月的数据在 sql 服务器中不起作用

[英]Getting previous month data not working in sql server

I am trying to get the previous month data according to the datetime in the column dynamically for example I have data like this我正在尝试根据列中的日期时间动态获取上个月的数据,例如我有这样的数据

在此处输入图像描述

Now I want the records previous than Opendt.现在我想要Opendt之前的记录。 The problem is that I am getting the record after Opendt but I am getting empty when I am getting the record before 1 month or 2 month of Opendt问题是我在 Opendt 之后获得记录,但是当我在 Opendt 的 1 个月或 2 个月之前获得记录时我变得空虚

this is the query i am writing这是我正在写的查询

select * from dbo.mytable where Valdate between OpenDt and dateadd(Month,-1,OpenDt)

the problem is that here -1 and -2 returning empty but when i am adding positive values 1, 2 and 3 I am getting the records after the OpenDt but not the before Dt Records.问题是这里 -1 和 -2 返回空但是当我添加正值 1、2 和 3 时,我得到的是 OpenDt 之后的记录,而不是之前的 Dt 记录。

I need the previous one or two month records before OpenDt我需要OpenDt之前的一两个月的记录

What is the data type of your Date columns?您的日期列的数据类型是什么? Are they of any of the date and/or time types described here https://docs.microsoft.com/en-us/sql/t-sql/functions/date-and-time-data-types-and-functions-transact-sql?view=sql-server-ver15 ?它们是此处描述的任何日期和/或时间类型https://docs.microsoft.com/en-us/sql/t-sql/functions/date-and-time-data-types-and-functions-事务-sql?view=sql-server-ver15 ?

If not, you may have to change the type for your queries as described here https://docs.microsoft.com/en-us/sql/t-sql/functions/try-cast-transact-sql?view=sql-server-ver15 (not recommended) OR reload the data with the correct types OR create new columns with correct types and update them with date/time values of your date columns.如果没有,您可能必须按照此处所述更改查询的类型https://docs.microsoft.com/en-us/sql/t-sql/functions/try-cast-transact-sql?view=sql- server-ver15 (不推荐)使用正确的类型重新加载数据创建具有正确类型的新列并使用日期列的日期/时间值更新它们。 And then use the new columns/correctly typed data in your queries.然后在查询中使用新列/正确键入的数据。

You need to reverse the BETWEEN.您需要反转 BETWEEN。 The lower value must always be first.较低的值必须始终是第一个。

SELECT * 
FROM dbo.mytable
WHERE Valdate BETWEEN dateadd(Month,-1,OpenDt) AND OpenDt

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

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