【发布时间】:2014-05-09 18:02:22
【问题描述】:
我正在尝试根据日期为总和分配不同的列。 这是我所拥有的:
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 是代码的去向。
【问题讨论】:
-
如果我回答了您的问题,请告诉我。我很高兴澄清任何可能遗漏或错误的内容。因为看起来你是一个相当新的用户,我也会添加一个欢迎! :) 请务必标记答案(在选票下方打勾)并在有人发布有用的内容时点赞。
-
“指定一列” .. 你能把你的案子说清楚吗?
-
@paqogomez 当我将这两个输入到那里时,它们得到的结果都是一样的,你知道这是为什么吗?
-
输入哪两个到哪里?你检查了吗my fiddle?
-
底线,这个查询有很多问题。我建议将这些想法分解为更小的查询并解决问题,然后将它们重新组合在一起会更直接。
标签: sql postgresql sum case between