将3个不同的“ CASE”列总计为三个不同的总数

时间:2019-03-05 04:29:02

标签: sql postgresql

我对此并不陌生,所以很抱歉如果我问错了这个问题。但是我试图从使用4种不同情况的表中获取4种不同的SUM。但是我只希望ID与总数一起列出一次。我会告诉你我有什么,我想得到什么。请尽可能提供帮助。

    SELECT schools.name, articles.competition_place,

    Case when articles.competition = 'yes' and competition_place = '1' then int '100'
       when articles.competition = 'yes' and competition_place = '2' then int '60'
       when articles.competition = 'yes' and competition_place = '3' then int '20'
    ELSE 0 end AS "Competition_Score",

    Case when articles.out_reach = 'yes' then int '30'
        ELSE 0 end AS "out_reach_Score",

    CASE when schools.school_id is not null then int '5'
        ELSE 0 end as "article_score",

    (Case when articles.competition = 'yes' and competition_place = '1' then int '100'
        when articles.competition = 'yes' and competition_place = '2' then int '60'
        when articles.competition = 'yes' and competition_place = '3' then int '20'
        ELSE 0 end) +
    (Case when articles.out_reach = 'yes' then int '30'
        ELSE 0 end) +
    (CASE when schools.school_id is not null then int '5'
        ELSE 0 end) as "total_score"
    from articles
    join clubs on articles.club_id = clubs.club_id
    join schools on clubs.school_id = schools.school_id

My table that I have

这就是我想要得到的。

This is the table I'm trying to get

这可能吗?

1 个答案:

答案 0 :(得分:1)

使用汇总和分组依据

SELECT schools.name, articles.competition_place,

sum(Case when articles.competition = 'yes' and competition_place = '1' then int '100'
   when articles.competition = 'yes' and competition_place = '2' then int '60'
   when articles.competition = 'yes' and competition_place = '3' then int '20'
ELSE 0 end) AS "Competition_Score",

sum(Case when articles.out_reach = 'yes' then int '30'
    ELSE 0 end) AS "out_reach_Score",

sum(CASE when schools.school_id is not null then int '5'
    ELSE 0 end) as "article_score",

sum((Case when articles.competition = 'yes' and competition_place = '1' then int '100'
    when articles.competition = 'yes' and competition_place = '2' then int '60'
    when articles.competition = 'yes' and competition_place = '3' then int '20'
    ELSE 0 end)) +
sum((Case when articles.out_reach = 'yes' then int '30'
    ELSE 0 end)) +
sum(CASE when schools.school_id is not null then int '5'
    ELSE 0 end)) as "total_score"
from articles
join clubs on articles.club_id = clubs.club_id
join schools on clubs.school_id = schools.school_id
group by schools.name, articles.competition_place