sql - SUM 3 个不同的“CASE”列,三个不同的总数
问题描述
我是新手,所以如果我问错了这个问题,我很抱歉。但我试图从使用 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
这就是我想要得到的。
这可能吗?
解决方案
使用聚合和分组依据
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
推荐阅读
- javascript - 在打字稿文件中使用 .subscribe 之外的数据
- python - 使用 %s 运算符在 Python 中创建 MySQL 表列
- r - R“survival”中weibull survreg模型预测的se.fit的置信区间
- vhdl - 使用带有 ADC 的双向 I2C 总线时的 VHDL 高“Z”
- php - 在 PHP 中提取 JSON 字符串的键
- c# - 如何在 C# Unity 中创建类型 Void 数组?
- python - 如何根据使用 selenium/python 的 Excel 工作表中给出的值从下拉列表中选择一个值
- java - 计时器归零时如何防止键盘事件
- reactjs - setTimeout() 输出一个非预期的数字/计时器
- powershell - 将“此文件夹”复制到网络驱动器(Robocopy 或 PowerShell)