table 的列总和,按 table 分区分组
sum columns of a table, grouping by table partition
我有一个 table 用于保存每日指标:
|DateID | Metric1 | Metric2|
20190501 24 34
20190502 25 56
..... .... ....
table 有超过 1.5 亿行。它按每月的 DateID 进行分区(每个分区包含从每月第一天到下个月第一天的 DateID 行)。我的一些分区:
rows pages comparison value
4205460 174009 less than 20180801
4205460 174097 less than 20180901
4069800 168449 less than 20181001
4205460 174009 less than 20181101
4069800 168433 less than 20181201
4205460 174097 less than 20190101
4205460 174009 less than 20190201
3798480 157201 less than 20190301
4205460 174097 less than 20190401
4069800 168449 less than 20190501
2984520 123545 less than 20190601
我想 select sum(metric1), sum(metric2)
,每月。
到目前为止我正在做的是创建一个临时 table 将 YYYYMM 保存为 MonthID 并在 substring(dateID,1,6) = MonthID
上加入我的 table 然后 select 总和按 MonthID 分组。然而,这太慢了。我认为如果我能以某种方式直接使用 table 的分区进行分组会更快。有什么办法吗?如果没有任何方法可以提高求和性能?
您可以尝试两个聚合级别:
select left(dateid, 6) as yyyymm,
sum(metric1), sum(metric2)
from (select dateid, sum(metric1) as metric1, sum(metric2) as metric2
from t
group by dateid
) t
group by left(dateid, 6)
order by yyyymm;
内部聚合仅在分区键上明确显示。
我应该注意,当分区键是聚合键时,我不知道 SQL 服务器是否在分区数据库上优化 group by
。然而,它可能,所以这值得一试。
我有一个 table 用于保存每日指标:
|DateID | Metric1 | Metric2|
20190501 24 34
20190502 25 56
..... .... ....
table 有超过 1.5 亿行。它按每月的 DateID 进行分区(每个分区包含从每月第一天到下个月第一天的 DateID 行)。我的一些分区:
rows pages comparison value
4205460 174009 less than 20180801
4205460 174097 less than 20180901
4069800 168449 less than 20181001
4205460 174009 less than 20181101
4069800 168433 less than 20181201
4205460 174097 less than 20190101
4205460 174009 less than 20190201
3798480 157201 less than 20190301
4205460 174097 less than 20190401
4069800 168449 less than 20190501
2984520 123545 less than 20190601
我想 select sum(metric1), sum(metric2)
,每月。
到目前为止我正在做的是创建一个临时 table 将 YYYYMM 保存为 MonthID 并在 substring(dateID,1,6) = MonthID
上加入我的 table 然后 select 总和按 MonthID 分组。然而,这太慢了。我认为如果我能以某种方式直接使用 table 的分区进行分组会更快。有什么办法吗?如果没有任何方法可以提高求和性能?
您可以尝试两个聚合级别:
select left(dateid, 6) as yyyymm,
sum(metric1), sum(metric2)
from (select dateid, sum(metric1) as metric1, sum(metric2) as metric2
from t
group by dateid
) t
group by left(dateid, 6)
order by yyyymm;
内部聚合仅在分区键上明确显示。
我应该注意,当分区键是聚合键时,我不知道 SQL 服务器是否在分区数据库上优化 group by
。然而,它可能,所以这值得一试。