带有列存储桶的SQL

带有列存储桶的SQL,sql,vertica,Sql,Vertica,我正在尝试对表示数据桶的列编写sql查询: 例如,如果我的数据是: title | value A | 1.2 A | 2.3 B | 0.5 B | 0.8 B | 1.7 我希望我的输出看起来像: title | count(0-1) | count(1-2) | count(2+) A | 0 | 1 | 1 B | 2 | 1 | 0 我能够通过编写多个查询

我正在尝试对表示数据桶的列编写
sql
查询:

例如,如果我的数据是:

title | value
A     | 1.2
A     | 2.3
B     | 0.5
B     | 0.8
B     | 1.7
我希望我的输出看起来像:

title | count(0-1) | count(1-2) | count(2+)
A     | 0          | 1          | 1
B     | 2          | 1          | 0
我能够通过编写多个查询得到这个结果,例如,包括:

WHERE value >= 0 AND value < 1
其中值>=0且值<1
获取表示每个bucket的表,然后合并这些表。我的问题是,我正在查询一个非常大的数据库,因此运行多个查询需要很长时间


在sql查询中是否有自动执行此操作的方法?

您可以使用条件聚合:

select title,
       sum(case when value >= 0 and value < 1 then 1 else 0 end) as bucket_0_1,
       sum(case when value >= 1 and value < 2 then 1 else 0 end) as bucket_1_2,
       sum(case when value >= 2 then 1 else 0 end) as bucket_2pl
from t
group by title;
选择标题,
求和(当值>=0且值<1时,则为1,否则为0结束)作为桶0\u 1,
求和(当值>=1且值<2时,则为1,否则为0结束)作为存储桶_1_2,
求和(当值>=2时,则为1,否则为0结束)作为存储桶
从t
按头衔分组;

您可以使用条件聚合:

select title,
       sum(case when value >= 0 and value < 1 then 1 else 0 end) as bucket_0_1,
       sum(case when value >= 1 and value < 2 then 1 else 0 end) as bucket_1_2,
       sum(case when value >= 2 then 1 else 0 end) as bucket_2pl
from t
group by title;
选择标题,
求和(当值>=0且值<1时,则为1,否则为0结束)作为桶0\u 1,
求和(当值>=1且值<2时,则为1,否则为0结束)作为存储桶_1_2,
求和(当值>=2时,则为1,否则为0结束)作为存储桶
从t
按头衔分组;
您可以执行以下操作:

select title, 
       sum(case when value >= 0 and value < 1 then 1 else 0 end),
       sum(case when value >= 1 and value < 2 then 1 else 0 end),
       sum(case when value >= 2 then 1 else 0 end) 
from table t
group by title'
选择标题,
总和(当值>=0且值<1时,则为1,否则为0结束),
总和(当值>=1且值<2时,则为1,否则为0结束),
总和(当值>=2时,则为1,否则为0结束)
来自表t
按标题分组'
您可以执行以下操作:

select title, 
       sum(case when value >= 0 and value < 1 then 1 else 0 end),
       sum(case when value >= 1 and value < 2 then 1 else 0 end),
       sum(case when value >= 2 then 1 else 0 end) 
from table t
group by title'
选择标题,
总和(当值>=0且值<1时,则为1,否则为0结束),
总和(当值>=1且值<2时,则为1,否则为0结束),
总和(当值>=2时,则为1,否则为0结束)
来自表t
按标题分组'

select sum( case when value>=0 and value<1 then 1 else 0 end )
as b_0_1',
sum( case when value>=1 and value<2 then 1 else 0 end )as b_1_2,
sum( case when value>2 then 1 else 0 end ) as b_2 ,tittle
from t group by title
选择sum(值>=0时的情况和值时的使用情况

select sum( case when value>=0 and value<1 then 1 else 0 end )
as b_0_1',
sum( case when value>=1 and value<2 then 1 else 0 end )as b_1_2,
sum( case when value>2 then 1 else 0 end ) as b_2 ,tittle
from t group by title

选择sum(当value>=0和value时,您可以使用
视图
s,并使用
索引
优化数据库运行多个查询需要很长时间。
是否确定查询越少=速度越快?您可以使用
视图
s,并使用
索引
优化数据库运行多个查询需要很长时间。
您确定查询越少=速度越快吗?