postgresql 分配给某个条件的两列之和

u3r8eeie  于 2023-02-04  发布在  PostgreSQL
关注(0)|答案(2)|浏览(199)

嗨,我试图获取存储到一个名称的两列的总数,然后获取一个条件,但我在第3行的“Rebound”名称上出错
offreb和defreb具有整数类型,并且一些值被存储为0(零)。

SELECT team, CONCAT(firstname,' ',lastname) AS name, SUM(offreb + defreb) AS Rebounds
FROM boxscore
WHERE round = 'Finals' AND game = 7 AND Rebounds > 0
ORDER BY team, Rebounds;
mlnl4t2r

mlnl4t2r1#

您希望按WHERE子句中的列进行筛选,而该列在执行WHERE子句时尚未计算。您可以使用子查询或具有。
应该是这样的:

SELECT team, CONCAT(firstname,' ',lastname) AS name, SUM(offreb + defreb) AS Rebounds
FROM boxscore
WHERE round = 'Finals' AND game = 7
GROUP BY team, CONCAT(firstname,' ',lastname)
HAVING SUM(offreb + defreb) > 0
ORDER BY team, Rebounds;
5anewei6

5anewei62#

这里使用HAVING子句解决了您的问题。
如果一个表已经使用GROUP BY进行了分组,但只对某些组感兴趣,则可以使用HAVING子句(很像WHERE子句)从结果中删除组。官方postgres docs

SELECT
  team,
  CONCAT(firstname,' ',lastname) AS name,
  SUM(offreb + defreb) AS "Rebounds"
FROM 
  boxscore
WHERE
  round = 'Finals' AND game = 7
GROUP BY
  team,
  CONCAT(firstname,' ',lastname)
HAVING
  SUM(offreb + defreb) > 0
ORDER BY
  team, "Rebounds";

请注意,不能在WHERE和GROUP BY子句中使用列别名,但可以在ORDER BY子句中使用列别名,并用双引号括起来以保持区分大小写。

相关问题