SQL 具有用于列的存储桶
SQL with buckets for columns
我正在尝试向表示数据桶的列编写 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
得到一个代表每个桶的table,然后合并table。我的问题是我正在查询一个非常大的数据库,所以 运行 多个查询需要很长时间。
在 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;
你可以这样做:
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'
用例
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
我正在尝试向表示数据桶的列编写 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
得到一个代表每个桶的table,然后合并table。我的问题是我正在查询一个非常大的数据库,所以 运行 多个查询需要很长时间。
在 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;
你可以这样做:
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'
用例
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