创建表视图,汇总行中的所有列以及行名等于列名的列的所有行

时间:2019-01-25 20:20:21

标签: sql postgresql

我有一个看起来像这样的postgresql表:

name      |rock|paper|scissors
__________|____|_____|________
rock      | .5 |  0  |   2
paper     | 2  |  1  |   0
scissors  | 1  |  4  |   2

我想创建一个postgresql视图,将每个名称的行和列加在一起,如下所示:

name      |strong|weak
__________|______|____
rock      |  2.5 | 2.5  
paper     |  3   | 5  
scissors  |  7   | 4  

我在第二张表中想要的是两列。一个是第一个表的行中所有列的总和,以名称分隔。第二列是该列等于名称的行的总和。


我可以使用strong列来工作,但是我不知道如何获取weak列。这是我最近的尝试。

SELECT 
    name, 
    (rock + paper + scissors) AS strong, 
    (sum(rock) + sum(paper) + sum(scissors)) AS weak 
FROM mytable 
GROUP BY name;

这只会产生一个表,其弱列等于强列,如下所示:

name      |strong|weak
__________|______|____
rock      |  2.5 | 2.5  
paper     |  3   | 3  
scissors  |  7   | 7  

我如何达到我想要的结果?

3 个答案:

答案 0 :(得分:2)

可以如下所示创建视图:

create view v1 as
select
  name,
  rock + paper + scissors as strong,
  (select
     sum(case 
       when t1.name = 'rock' then t2.rock
       when t1.name = 'paper' then t2.paper
       when t1.name = 'scissors' then t2.scissors
       end
     ) from mytable t2
  ) as weak
from mytable t1

答案 1 :(得分:2)

这可以使用条件窗口总和来完成,例如:

SELECT 
    name, 
    (rock + paper + scissors) AS strong,
    CASE name
        WHEN 'rock'     THEN SUM(rock)     OVER()
        WHEN 'paper'    THEN SUM(paper)    OVER()
        WHEN 'scissors' THEN SUM(scissors) OVER()
    END AS weak
FROM mytable 

Demo

答案 2 :(得分:2)

您可以为此使用窗口功能:

select name, (rock + paper + scissors) as strong,
       (case when name = 'rock' then sum(rock) over ()
             when name = 'paper' then sum(paper) over ()
             when name = 'scissors' then sum(scissors) over ()
        end) as weak
from t;