我正在尝试根据日期为总和分配不同的列。 这就是我所拥有的:
SELECT SUM(amount) CASE WHEN date BETWEEN '1/1/13' AND '1/1/14' THEN Last_yr_tot
WHEN date BETWEEN '1/1/14' AND 'now' THEN YTD
我的整个查询。
select fd.location_cd
,round(sum(case when fd.fs_dt between '1/1/13' and '12/31/13' then amount else 0 end)::numeric, 0) as Last_yr
,round(sum(case when fd.fs_dt between '1/1/14' and current_date then amount else 0 end)::numeric, 0) as YTD
,round(sum(case when date_part('month', fd.fs_dt) = 1 then amount end)::numeric, 0) January_data
,round(sum(case when date_part('month', fd.fs_dt) = 2 then amount end)::numeric, 0) February_data
,round(sum(case when date_part('month', fd.fs_dt) = 3 then amount end)::numeric, 0) March_data
,round(sum(case when date_part('month', fd.fs_dt) = 4 then amount end)::numeric, 0) April_data
,round(sum(case when date_part('month', fd.fs_dt) = 5 then amount end)::numeric, 0) May_data
,round(sum(case when date_part('month', fd.fs_dt) = 6 then amount end)::numeric, 0) June_data
,round(sum(case when date_part('month', fd.fs_dt) = 7 then amount end)::numeric, 0) July_data
,round(sum(case when date_part('month', fd.fs_dt) = 8 then amount end)::numeric, 0) August_data
,round(sum(case when date_part('month', fd.fs_dt) = 9 then amount end)::numeric, 0) September_data
,round(sum(case when date_part('month', fd.fs_dt) = 10 then amount end)::numeric, 0) October_data
,round(sum(case when date_part('month', fd.fs_dt) = 11 then amount end)::numeric, 0) November_data
,round(sum(case when date_part('month', fd.fs_dt) = 12 then amount end)::numeric, 0) December_data
from financial_acct fa
join financial_data fd
on fd.acct_no = fa.acct_no
inner join (select sum(fd.amount)
from financial_data fd
where fd.fs_dt between '1/1/13' and '1/1/14'
) Last_yr
on fa.acct_no = fd.acct_no
where fa.acct_no = '799-' and fd.fs_dt between '1/1/14' and 'now'
group by fd.location_cd
,fd.fs_dt
order by fd.location_cd
要求我将整个查询放入帖子中。我会遵守,但它需要更多细节。 acct_no是帐号。 fs_dt是日期。 location_cd是代码的去向。
答案 0 :(得分:2)
您需要将这些分成两列。每个都查看日期范围并返回金额值或零
select
sum(case when datecolumn between '1/1/13' and '1/1/14' then amount else 0 end) as last_yr_tot,
sum(case when datecolumn between '1/1/14' and current_date then amount else 0 end) as ytd
from
myTable
请注意,datecolumn
和myTable
必须替换为您自己的日期列和表名。由于date
是postgresql中的保留字,因此它看起来不像列名。