[英]Why does case statement return null values
I am looking to group bmi-ranges and the average child per range.我正在寻找对 bmi 范围和每个范围的平均孩子进行分组。 Everything seems to check out but i am recieve a null group when there are no nulls in the data set.
一切似乎都检查过了,但是当数据集中没有空值时,我收到了一个 null 组。 This is the code:
这是代码:
With new_table as
(
SELECT
case
when bmi <15 THEN 'Under 15'
when bmi BETWEEN 15 AND 20 THEN '20 and under'
when bmi BETWEEN 20 AND 29.99 THEN '20-29'
when bmi BETWEEN 30 AND 39.99 THEN '30-39'
when bmi BETWEEN 40 AND 49.99 THEN '40-49'
when bmi >50 THEN '50 and over'
END as bmi_range,
AVG(children) as children
FROM
health_in.data_in
WHERE
children != 0
GROUP BY
case
when bmi <15 THEN 'Under 15'
when bmi BETWEEN 15 AND 20 THEN '20 and under'
when bmi BETWEEN 20 AND 29.99 THEN '20-29'
when bmi BETWEEN 30 AND 39.99 THEN '30-39'
when bmi BETWEEN 40 AND 49.99 THEN '40-49'
when bmi >50 THEN '50 and over'
END
)
SELECT
*
FROM
new_table
GROUP BY
bmi_range,
children
ORDER BY
bmi_range asc
there are no rows with in the source table health_in.data_in
with a null bmi (or with any value less than 15 or more than 60).源表
health_in.data_in
中没有具有 null bmi(或任何小于 15 或大于 60 的值)的行。
Why does bmi_range then include null values?为什么 bmi_range 然后包含 null 值?
The CASE
does not cover all possible values, eg 50, or 29.995. CASE
并未涵盖所有可能的值,例如 50 或 29.995。 Also there is no need to repeat the values because a CASE
expression uses short-circuit evaluation, ie it stops as soon as a match is found.也不需要重复这些值,因为
CASE
表达式使用短路评估,即一旦找到匹配项就停止。
You can rewrite it as:您可以将其重写为:
CASE
WHEN bmi < 15 THEN 'Under 15'
WHEN bmi < 20 THEN '15-20'
WHEN bmi < 30 THEN '20-29'
WHEN bmi < 40 THEN '30-39'
WHEN bmi < 50 THEN '40-49'
ELSE '50 and over'
END
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.