Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何在Postgres中为同一列的总和创建两列?_Sql_Postgresql - Fatal编程技术网

Sql 如何在Postgres中为同一列的总和创建两列?

Sql 如何在Postgres中为同一列的总和创建两列?,sql,postgresql,Sql,Postgresql,我有一个包含以下列的表: Type | Date | Amount 当类型具有类似“E”的值时,我使用SUM函数在“Amount”列中添加值(如SUM1)。 我的问题是: select to_char("Date", 'Mon') as mon, extract(year from "Date") as yyyy, sum("Amount") as SUM1 from "Transactions" where "Type" LIKE 'E%' and "Date" betwee

我有一个包含以下列的表:

Type | Date | Amount
当类型具有类似“E”的值时,我使用SUM函数在“Amount”列中添加值(如SUM1)。 我的问题是:

select 
  to_char("Date", 'Mon') as mon,
  extract(year from "Date") as yyyy,
  sum("Amount") as SUM1 
from "Transactions"
where "Type" LIKE 'E%' and "Date" between '01/01/2015' and '08/31/2015'
group by 1,2
order by yyyy, mon;
这将产生如下行:

mon | yyyy | SUM1
mon | yyyy | SUM1 | SUM2
然而,我想做的是还显示另一个sum列(SUM2),显示从“Amount”中添加的值的总和,其中“Type”类似于“p”,因此显示如下行:

mon | yyyy | SUM1
mon | yyyy | SUM1 | SUM2

您可以使用case表达式作为sum函数的参数,以选择按如下方式求和的内容:

select 
    to_char("Date", 'Mon') as mon,
    extract(year from "Date") as yyyy,
    sum(case when "Type" LIKE 'E%' then "Amount" else 0 end) as SUM1,
    sum(case when "Type" LIKE 'P%' then "Amount" else 0 end) as SUM2
from "Transactions"
where "Date" between '01/01/2015' and '08/31/2015'
  and "Type" like 'E%' or "Type" like 'P%'
group by 1,2
order by yyyy, mon;

取决于您的PostgreSQL版本。对于旧款,您可以使用
CASE
进行条件求和:

select to_char("Date", 'Mon') as mon,
extract(year from "Date") as yyyy,
sum(CASE WHEN "Type" LIKE 'E%' then "Amount" ELSE 0 END) as SUM1,
sum(CASE WHEN "Type" LIKE 'P%' then "Amount" ELSE 0 END) as SUM2
from "Transactions"
where "Date" between '01/01/2015' and '08/31/2015'
group by 1,2
order by yyyy, mon;
或者,如果您使用的是PostgreSQL 9.4或更高版本,则可以使用更好的
过滤器
语法:

select to_char("Date", 'Mon') as mon,
extract(year from "Date") as yyyy,
sum("Amount") FILTER (WHERE "Type" LIKE 'E%') as SUM1,
sum("Amount") FILTER (WHERE "Type" LIKE 'P%') as SUM2
from "Transactions"
where "Date" between '01/01/2015' and '08/31/2015'
group by 1,2
order by yyyy, mon;