PostgreSQL,返回包含年份发票计数的列

时间:2014-06-19 22:48:42

标签: sql postgresql postgresql-9.1

2桌

  1. 公司
  2. 发票
  3. 我想返回以下内容

    Company Name  |  invoice_total_2014   | invoice_total_2013
    ----------------------------------------------------------
    Company A     | 2000                  | 1500
    Company B     | 1000                  | 1000
    

    所以基本上它正在对invoice_total列进行某种查询,其中函数之间的日期为。

    这可以在postgreSQL中使用吗?

1 个答案:

答案 0 :(得分:2)

select
    name,
    sum(
        total * (extract(year from created_at) = 2014)::integer
    ) as invoice_total_2014,
    sum(
        total * (extract(year from created_at) = 2013)::integer
    ) as invoice_total_2013
from invoice
group by name

将布尔值转换为整数会导致0或1

或传统的case

select
    name,
    sum(
        case extract(year from created_at) when 2014 then total end
    ) as invoice_total_2014,
    sum(
        case extract(year from created_at) when 2013 then total end
    ) as invoice_total_2013
from invoice
group by name