Debian Codegraph @

src/main/org/h2/expression/aggregate/AggregateDataCovar.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.expression.aggregate;
7
8 import org.h2.engine.SessionLocal;
9 import org.h2.message.DbException;
10 import org.h2.value.Value;
11 import org.h2.value.ValueDouble;
12 import org.h2.value.ValueNull;
13
14 /**
15 * Data stored while calculating a COVAR_POP, COVAR_SAMP, or REGR_SXY aggregate.
16 */
17 final class AggregateDataCovar extends AggregateDataBinarySet {
18
19 private final AggregateType aggregateType;
20
21 private long count;
22
23 private double sumY, sumX, sumYX;
24
25 /**
26 * @param aggregateType
27 * the type of the aggregate operation
28 */
29 AggregateDataCovar(AggregateType aggregateType) {
30 this.aggregateType = aggregateType;
31 }
32
33 @Override
34 void add(SessionLocal session, Value yValue, Value xValue) {
35 double y = yValue.getDouble(), x = xValue.getDouble();
36 sumY += y;
37 sumX += x;
38 sumYX += y * x;
39 count++;
40 }
41
42 @Override
43 Value getValue(SessionLocal session) {
44 double v;
45 switch (aggregateType) {
46 case COVAR_POP:
47 if (count < 1) {
48 return ValueNull.INSTANCE;
49 }
50 v = (sumYX - sumX * sumY / count) / count;
51 break;
52 case COVAR_SAMP:
53 if (count < 2) {
54 return ValueNull.INSTANCE;
55 }
56 v = (sumYX - sumX * sumY / count) / (count - 1);
57 break;
58 case REGR_SXY:
59 if (count < 1) {
60 return ValueNull.INSTANCE;
61 }
62 v = sumYX - sumX * sumY / count;
63 break;
64 default:
65 throw DbException.getInternalError("type=" + aggregateType);
66 }
67 return ValueDouble.get(v);
68 }
69
70 }