如何在sql中每月获得不同的数字?

时间:2014-05-09 00:16:57

标签: sql parameters inner-join between

我要做的是每月获得一笔金额。

这会有用吗?

SELECT @location
       ,sum(x.amount) as Tot_amount
FROM this_table2 y

    INNER JOIN 
       (SELECT 
            SUM(x.amount)  
        FROM 
            this_table x 
        WHERE 
            x.date BETWEEN '1/1/14' AND '1/31/14') January_tot

LEFT JOIN this_table2 y
       on x.no = y.no
WHERE y.desc = 'INCOME' AND x.date between '1/1/14' and 'now 

如果确实有效,有没有办法为年份设置参数?另外,我如何在此之后放置where子句?

1 个答案:

答案 0 :(得分:1)

我发现了如何做到这一点,date_part函数对此至关重要。

select @location
      ,sum(x.amount) as Tot_amount
      ,sum(case when date_part('month', x.date) = 1 and date_part('year', x.date) = 2014 then amount end) as January_Tot
      sum(case when date_part('month', x.date) = 2 and date_part('year', x.date) = 2014 then amount end) as February_Tot

left join this_table2 y
      on x.no = y.no
where y.desc = 'INCOME' and x.date between '1/1/14' and current_date