Case in select after sum?

2019-08-29 00:17发布

问题:

I'm trying to assign a different column to a sum depending on the dates. Here's what I have:

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

My entire query.

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

It was requested that I put my entire query into the post. I will comply, but it needs more details. acct_no is account number. fs_dt is the date. location_cd is where the code is going.

回答1:

You need to split these out into two columns. Each looking at the date range and returning the amount value or zero

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

Check this fiddle

Note that datecolumn and myTable must be replaced by your own date column and table names. As date is a reserved word in postgresql, it doesnt look much like a column name.