如何在SQL中的特定月份的第一天和最后一天之间获取数据?
以下是sql查询请帮忙
DECLARE @mydate DATETIME
SELECT @mydate = GETDATE()
select TransactionCode from ReceiptsPayments
where ReferenceDate >= (SELECT CONVERT(VARCHAR(25),
DATEADD(dd,-(DAY(@mydate)-1),@mydate),
101) AS Date_Value)
AND ReferenceDate <= (SELECT CONVERT(VARCHAR(25),
DATEADD(dd,
-(DAY(DATEADD(mm,1,@mydate))),
DATEADD(mm,1,@mydate)),
101))
GO
答案 0 :(得分:4)
试试这个 -
DECLARE @mydate DATETIME
SELECT @mydate = GETDATE()
SELECT TransactionCode
FROM dbo.ReceiptsPayments
WHERE MONTH(ReferenceDate) = MONTH(@mydate)
AND YEAR(ReferenceDate) = YEAR(@mydate)
答案 1 :(得分:3)
select TransactionCode
from ReceiptsPayments
where
month(ReferenceDate) = month(@mydate)
and
year(ReferenceDate) = year(@mydate) ;
答案 2 :(得分:0)
DECLARE @mydate DATETIME
SELECT @mydate = GETDATE()
select TransactionCode
from ReceiptsPayments
where ReferenceDate >= DATEADD(month, DATEDIFF(month, 0, @mydate), 0)
and ReferenceDate <= DATEADD(day, -1, DATEADD(month, DATEDIFF(month, 0, @mydate) + 1, 0))
答案 3 :(得分:0)
我自己使用DATEADD
/ DATEDIFF
模式:
select TransactionCode from ReceiptsPayments
where
ReferenceDate >= DATEADD(month,DATEDIFF(month,'20010101',GETDATE()),'20010101') and
ReferenceDate <= DATEADD(month,DATEDIFF(month,'20010101',GETDATE()),'20010131')
它有点可爱,因为当它被要求在任何月份的31日添加几个月时,它会自动调整到它到达的月份的正确结束日期。
此外,如果您的列中有时间,则更好的查询是:
select TransactionCode from ReceiptsPayments
where
ReferenceDate >= DATEADD(month,DATEDIFF(month,'20010101',GETDATE()),'20010101') and
ReferenceDate < DATEADD(month,DATEDIFF(month,'20010101',GETDATE()),'20010201')
然后使用下个月的第一天进行<
比较。对于具有时间分量的datetime
,这通常更好。