我有一个问题与我之前的帖子有关(对于参考:SQL - How to find optimal performance numbers for query)
基本上,我现在正尝试使用CASE WHEN函数来创建各种不同的组。例如,按照上一篇文章中的示例,我有以下内容:
SELECT
Vehicle_type,
case when Number_of_passengers::numeric = 0 then 'cat=0'
when Number_of_passengers::numeric < 2 then 'cat1<2'
when Number_of_passengers::numeric < 3 then 'cat1<3'
when Number_of_passengers::numeric < 4 then 'cat1<4'
when Number_of_passengers::numeric < 5 then 'cat1<5'
when Number_of_passengers::numeric < 6 then 'cat1<6'
when Number_of_passengers::numeric < 7 then 'cat1<7'
when Number_of_passengers::numeric > 2 then 'cat1>2'
when Number_of_passengers::numeric > 3 then 'cat1>3'
when Number_of_passengers::numeric > 4 then 'cat1>4'
when Number_of_passengers::numeric > 5 then 'cat1>5'
when Number_of_passengers::numeric > 6 then 'cat1>6'
when Number_of_passengers::numeric > 7 then 'cat1>7'end as category1,
case when Number_of_doors::numeric = 0 then 'cat2=0'
when Number_of_doors::numeric > 2 then 'cat2>2'
when Number_of_doors::numeric > 3 then 'cat2>3'
when Number_of_doors::numeric > 4 then 'cat2>4'
when Number_of_doors::numeric > 5 then 'cat2>5'
when Number_of_doors::numeric > 6 then 'cat2>6'
when Number_of_doors::numeric > 7 then 'cat2>7'
when Number_of_doors::numeric < 2 then 'cat2<2'
when Number_of_doors::numeric < 3 then 'cat2<3'
when Number_of_doors::numeric < 4 then 'cat2<4'
when Number_of_doors::numeric < 5 then 'cat2<5'
when Number_of_doors::numeric < 6 then 'cat2<6'
when Number_of_doors::numeric < 7 then 'cat2<7' end as category2,
round(sum(case when in_accident='t' then 1.0 end)/ count(*),3) as accident_rate,
FROM Accidents
GROUP by 1,2,3
这实际上是在格式方面给我正确的输出,但是,我在'accident_rate'列中收到的数字会有所不同。
如果我运行了整个查询,那么对于组来说,我会得到一个不同的accident_rate,而不是单独查看组。
要解释一下,如果我运行上述查询并查看:Car,Number_of_passengers&gt; 2和Number_of_doors&gt; 2,我的事故率可能是60%。
然而,如果我将查询运行为:
SELECT
Vehical_type,
case when Number_of_passengers::numeric > 2 then 'cat1>2' end as category1,
case when Number_of_doors::numeric > 2 then 'cat2>2' end as category2,
round(sum(case when in_accident='t' then 1.0 end)/ count(*),3) as accident_rate,
FROM Accidents
GROUP by 1,2,3
我的意外率可能只有20%。
有什么建议吗?
由于