获得当月?

时间:2014-06-10 17:18:54

标签: sql postgresql date

在SQL查询中,我只需要从当前月份获取一些数据。为了获得特定月份,我会这样做。

select (case when date_part('month', date) = 3 and date_part('year', date) = 2014 then amount end)
       ,(case when date_part('month', date) = 3 and date_part('year', date) = 2013 then amount end
from <table>

我的主要目的是获得今年的当月,以及上一年的同月。

这就是我想要的

select current_month(case when date_part('year', date) = 2014 then amount end) as current
       ,(case when current_month and date_part('year', date) = 2013 then amount end) as last_year

3 个答案:

答案 0 :(得分:1)

您可以使用now()current_timestamp来获取当前时间,然后是当前月份,年份和去年:

select (case when date_part('month', date) = extract(month from now()) and date_part('year', date) = extract(year from now()) then amount end)
       ,(case when date_part('month', date) = extract(month from now()) and date_part('year', date) = extract(year from now())-1 then amount end
from <table>

答案 1 :(得分:1)

使用评论反馈:

select (case when date_part('month', date) = date_part('month',current_Timestamp) and 
        date_part('year', date) = date_part('Year',current_TimeStamp) then amount end)
       ,(case when date_part('month', date) = date_part('month',current_Timestamp) and 
        date_part('year', date) = date_part('Year',current_TimeStamp)-1 then amount end
from <table>

和示例小提琴:sqlfiddle.com /#!15 / e495f / 1/0

答案 2 :(得分:1)

尝试以下SQL代码,以便获得当前的月份和年份

 select DATEPART(mm,GETDATE())
 select DATEPART(YY,GETDATE())

所以你的完整代码是:

select (case when DATEPART(YY,GETDATE()) = 3 and DATEPART(YY,GETDATE()) = 2014 then amount end)
   ,(case when DATEPART(YY,GETDATE()) = 3 and DATEPART(YY,GETDATE()) = 2013 then amount end
from <table>