【问题标题】:Case in select after sum?总和后选择的情况?
【发布时间】: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


【解决方案1】:

您需要将它们分成两列。每次查看日期范围并返回金额值或零

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

请注意,datecolumnmyTable 必须替换为您自己的日期列和表名。由于date是postgresql中的保留字,所以看起来不像是列名。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-22
    • 2013-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多