sql - Why does Case written this way bring a 'ghost' row in my table?
问题描述
Question: Write a query that calculates the combined weight of all underclass players (FR/SO) in California as well as the combined weight of all upperclass players (JR/SR) in California.
My Answer:
SELECT
CASE
WHEN state = 'CA' AND year IN ('FR', 'SO')
THEN 'underclass'
WHEN state = 'CA' AND year IN ('JR', 'SR')
THEN 'upperclass'
ELSE NULL
END AS class_divide,
SUM(weight) AS combined_weights
FROM benn.college_football_players
GROUP BY 1
| class_divide | combined_weights |
+--------------+------------------+
| | 5326369.0 |
| upperclass | 262452.0 |
| underclass | 274374.0 |
Correct Answer:
SELECT
CASE
WHEN year IN ('FR', 'SO')
THEN 'underclass'
WHEN year IN ('JR', 'SR')
THEN 'upperclass'
ELSE NULL
END AS class_group,
SUM(weight) AS combined_player_weight
FROM benn.college_football_players
WHERE state = 'CA'
GROUP BY 1
Why does it work to add
Where state = 'CA'
after the CASE and not within the CASE? Thanks in advance.
Bonus question: Is naming columns using numbers i.e Group by 1 a feature unique to PostgreSQL?
解决方案
The CASE
expression does not filter out any rows. So the non-CA rows are all grouped into the NULL
group.
Note that ELSE NULL
is redundant, because that is the default if nothing matches.
As for GROUP BY 1
. . . This is definitely not standard syntax but most modern databases seems to support it. Of course, most modern databases also use Postgres as their code base, because the Postgres license allows its code base to be incorporated into paying products.
推荐阅读
- scala - 案例类的字符串字段的修剪值
- c# - 无法使用 sendgrid api 发送附件
- python - Python中的蛇游戏使用Turtle图形错误
- python - 不确定从 Python 的这一点到哪里去?
- ios - 是否可以从一个 Apple Watch 应用程序重定向到另一个 Apple Watch?
- python - 从 panda DataFrame 创建一个 pd.Series 列表
- python - 如何在子类中执行和注入策略
- cuda - Cuda 内核中的数据组织
- php - 如何将 HTML 元素的文本更改为 PHP 中的另一个元素?
- c++ - 如何在 Visual Studio 2018 或 2019 中禁用空格键智能感知提交?