在不同条件下选择同一表的列两次

时间:2019-07-17 09:32:48

标签: sql postgresql odoo odoo-11

我正在使用Odoo11并使用psql。而且我想在不同条件下为同一张表选择两次相同的列,为此,我使用了case语句,但得到了输出,但没有达到预期的效果。因为我要在单行中输出,但要在两行中输出。

查询

 SELECT project_id,
    CASE WHEN project_type = 'Internal'  THEN SUM(unit_amount) END,
    CASE WHEN project_type = 'Project' THEN SUM(unit_amount) END 
FROM account_analytic_line where project_id = 347 GROUP BY project_id,project_type

输出屏幕截图: enter image description here

对于上面的屏幕截图,它为同一project_id生成两行,并希望在同一行中为同一project_id生成这些列。

预先感谢

1 个答案:

答案 0 :(得分:2)

要在一行中获得结果,可以使用窗口函数:

select distinct on (project_id)
project_id,
sum(unit_amount) FILTER (where project_type = 'Internal') over(PARTITION BY project_id) as intern, 
sum(unit_amount) FILTER (where project_type = 'Project') over(PARTITION BY project_id) as project
FROM account_analytic_line 

使用适合的where子句扩展。