SQL QUERY从25(上个月)到25(当前月)

时间:2018-01-26 16:15:15

标签: sql sql-server

我想查询从上个月的第25天到当月的25个。示例:25/12 / 2017-25 / 01/2018

我不能做像transaction_date> = getdate() - 31这样的事情,因为有几个月有28,29天。

谢谢!

6 个答案:

答案 0 :(得分:2)

您可以使用:

SELECT *
FROM your_tab
WHERE transaction_date 
BETWEEN DATEFROMPARTS(IIF(MONTH(GETDATE()) = 1,YEAR(GETDATE())-1,YEAR(GETDATE())),
                      IIF(MONTH(GETDATE()) = 1, 12 , MONTH(GETDATE())-1)
                      ,25) 
          AND DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 25);

答案 1 :(得分:2)

一个简单的方法

where 
    transaction_date between dateadd(dd, 25, eomonth(getdate(),-2)) 
    and dateadd(dd, 25, eomonth(getdate(),-1))

答案 2 :(得分:1)

我建议DATEFROMPARTS与设定日期约会,并从头开始减去1个月:

WHERE [transaction_date] BETWEEN DATEADD(month, -1, DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 25)) AND DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 25)

答案 3 :(得分:1)

您可以使用日期时间功能从日期中减去一个月:

-- Feb 2016 is 29 days
select dateadd(month, -1, '2016-01-25 00:00')
>> 2015-12-25 00:00:00.000
select dateadd(month, -1, '2016-02-25 00:00')
>> 2016-01-25 00:00:00.000
select dateadd(month, -1, '2016-03-25 00:00')
>> 2016-02-25 00:00:00.000

-- Feb 2017 is 28 days
select dateadd(month, -1, '2017-01-25 00:00')
>> 2016-12-25 00:00:00.000
select dateadd(month, -1, '2017-02-25 00:00')
>> 2017-01-25 00:00:00.000
select dateadd(month, -1, '2017-03-25 00:00')
>> 2017-02-25 00:00:00.000


declare @thatDate datetime = '2017-01-25 00:00'

select *
from ThisTable
where ThisDate between dateadd(month, -1, @thatDate) and @thatDate

答案 4 :(得分:0)

如果您使用的是mysql,则可能会起作用:

SELECT * 
FROM SOME_TABLE
WHERE transaction_date 
BETWEEN 
    DATE_FORMAT(NOW(), '%Y-%m-25') - INTERVAL 1 MONTH
AND 
    DATE_FORMAT(NOW(), '%Y-%m-25')

答案 5 :(得分:-1)

您可以采取以下措施:

    Select fields from table
    where whateverDate > '25/12/2017' and
    whateverDate < '25/01/2018'