【发布时间】:2021-12-02 19:46:47
【问题描述】:
我有 animaltable 表:
| 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 |
我怎样才能做到这一点?如何在视图中添加额外的“动物”列?
【问题讨论】:
标签: sql postgresql sql-view
我有 animaltable 表:
| 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 |
我怎样才能做到这一点?如何在视图中添加额外的“动物”列?
【问题讨论】:
标签: sql postgresql sql-view
UNION ALL 不同的动物,在派生表(即子查询)中。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 与“常量表”一起使用(使用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;
【讨论】: