View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *     http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.shardingsphere.sharding.merge.dql.groupby.aggregation;
19  
20  import lombok.RequiredArgsConstructor;
21  
22  import java.math.BigDecimal;
23  import java.math.RoundingMode;
24  import java.util.Collection;
25  import java.util.LinkedHashSet;
26  import java.util.List;
27  
28  /**
29   * Distinct average aggregation unit.
30   */
31  @RequiredArgsConstructor
32  public final class DistinctAverageAggregationUnit implements AggregationUnit {
33      
34      private BigDecimal count;
35      
36      private BigDecimal sum;
37      
38      private final Collection<Comparable<?>> countValues = new LinkedHashSet<>();
39      
40      private final Collection<Comparable<?>> sumValues = new LinkedHashSet<>();
41      
42      @Override
43      public void merge(final List<Comparable<?>> values) {
44          if (null == values || null == values.get(0) || null == values.get(1)) {
45              return;
46          }
47          if (countValues.add(values.get(0)) && sumValues.add(values.get(0))) {
48              if (null == count) {
49                  count = BigDecimal.ZERO;
50              }
51              if (null == sum) {
52                  sum = BigDecimal.ZERO;
53              }
54              count = count.add(new BigDecimal(values.get(0).toString()));
55              sum = sum.add(new BigDecimal(values.get(1).toString()));
56          }
57      }
58      
59      @Override
60      public Comparable<?> getResult() {
61          if (null == count || BigDecimal.ZERO.equals(count)) {
62              return count;
63          }
64          // TODO use metadata to fetch float number precise for database field
65          return sum.divide(count, 4, RoundingMode.HALF_UP);
66      }
67  }