Postgres 添加列类别以根据特定列的总和查看

Postgres add column category to view base on sum of specific column

我有 动物table table:

id dog_amount cat_amount bird_amount
1 4 4 6
2 2 4 5
3 2 1 3

我想创建这样的视图:

id animal total
1 dogs 8
2 cats 9
3 birds 14

我怎样才能做到这一点?如何在视图中添加额外的列“动物”?

UNION ALL不同的动物,在派生table(即子查询。)GROUP BY其结果。

create view animalview as

select animal, SUM(total)
from
(
    select 'dogs' animal, dog_amount   as total   from animaltable
    UNION ALL 
    select 'cats' animal, cat_amount   as total   from animaltable
    UNION ALL
    select 'birds' animal, bird_amount as total   from animaltable
) dt
group by animal

另一种获得所需结果的方法,首先我在子查询(一行)中获取每只动物的总数,然后使用 LATERAL JOIN 和“常量 table”(使用 VALUES):

CREATE VIEW animals_view AS

SELECT s.*
FROM (SELECT SUM(dog_amount) AS dogs, SUM(cat_amount) AS cats, SUM(bird_amount) AS birds
      FROM animaltable) AS t
JOIN LATERAL (VALUES (1, 'dogs', t.dogs), (2, 'cats', t.cats), (3, 'birds', t.birds)) AS s(id, animal, total) ON TRUE;