You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iotdb.apache.org by ja...@apache.org on 2023/01/17 12:29:31 UTC

[iotdb] branch master updated: [IOTDB-5382]Support DIFF as built-in scalar function in IoTDB

This is an automated email from the ASF dual-hosted git repository.

jackietien pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/iotdb.git


The following commit(s) were added to refs/heads/master by this push:
     new bcf1b923ab [IOTDB-5382]Support DIFF as built-in scalar function in IoTDB
bcf1b923ab is described below

commit bcf1b923abd2dc49ac80b630df4fcd97c620888e
Author: Weihao Li <60...@users.noreply.github.com>
AuthorDate: Tue Jan 17 20:29:24 2023 +0800

    [IOTDB-5382]Support DIFF as built-in scalar function in IoTDB
---
 .../Operators-Functions/Variation-Trend.md         |  63 ++++
 docs/zh/UserGuide/Operators-Functions/Overview.md  |   5 +
 .../Operators-Functions/Variation-Trend.md         |  63 ++++
 .../apache/iotdb/itbase/constant/TestConstant.java |   1 +
 .../scalar/IoTDBDiffFunction2IT.java               |  45 +++
 .../scalar/IoTDBDiffFunction3IT.java               |  45 +++
 .../scalar/IoTDBDiffFunctionIT.java                | 346 +++++++++++++++++++++
 .../commons/udf/builtin/BuiltinScalarFunction.java |  59 ++++
 .../org/apache/iotdb/db/constant/SqlConstant.java  |   3 +
 .../apache/iotdb/db/mpp/plan/analyze/Analysis.java |  12 +
 .../iotdb/db/mpp/plan/analyze/AnalyzeVisitor.java  |  18 ++
 .../db/mpp/plan/analyze/ExpressionAnalyzer.java    |  33 ++
 .../mpp/plan/analyze/ExpressionTypeAnalyzer.java   |   7 +
 .../plan/expression/multi/FunctionExpression.java  |  13 +-
 .../visitor/ColumnTransformerVisitor.java          |  23 ++
 .../visitor/IntermediateLayerVisitor.java          |  22 ++
 .../plan/planner/distribution/SourceRewriter.java  |  14 +-
 .../unary/DiffFunctionColumnTransformer.java       |  67 ++++
 .../transformer/unary/DiffFunctionTransformer.java | 103 ++++++
 .../apache/iotdb/db/utils/TypeInferenceUtils.java  |  29 ++
 .../plan/distribution/AlignedByDeviceTest.java     | 108 +++++++
 21 files changed, 1072 insertions(+), 7 deletions(-)

diff --git a/docs/UserGuide/Operators-Functions/Variation-Trend.md b/docs/UserGuide/Operators-Functions/Variation-Trend.md
index f412c7c0d1..1853d1f48e 100644
--- a/docs/UserGuide/Operators-Functions/Variation-Trend.md
+++ b/docs/UserGuide/Operators-Functions/Variation-Trend.md
@@ -51,4 +51,67 @@ Result:
 +-----------------------------+-------------------+-------------------------------+--------------------------+---------------------------------------+--------------------------+---------------------------------------+
 Total line number = 5
 It costs 0.014s
+```
+
+| Function Name | Allowed Input Series Data Types | Attributes                                                                                                                                                                                                                                                                                              | Output Series Data Type | Description                                                                                                          [...]
+|---------------|---------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------|--------------------------------------------------------------------------------------------------------------------- [...]
+| DIFF          | INT32 / INT64 / FLOAT / DOUBLE  | `ignoreNull`:optional,default is true. If is true, the previous data point is ignored when it is null and continues to find the first non-null value forwardly. If the value is false, previous data point is not ignored when it is null, the result is also null because null is used for subtraction | DOUBLE                  | Calculates the difference between the value of a data point and the value of the previous data point. There is no co [...]
+
+### Example
+
+#### RawData
+
+``` 
++-----------------------------+------------+------------+
+|                         Time|root.test.s1|root.test.s2|
++-----------------------------+------------+------------+
+|1970-01-01T08:00:00.001+08:00|           1|         1.0|
+|1970-01-01T08:00:00.002+08:00|           2|        null|
+|1970-01-01T08:00:00.003+08:00|        null|         3.0|
+|1970-01-01T08:00:00.004+08:00|           4|        null|
+|1970-01-01T08:00:00.005+08:00|           5|         5.0|
+|1970-01-01T08:00:00.006+08:00|        null|         6.0|
++-----------------------------+------------+------------+
+```
+
+#### Not use `ignoreNull` attribute (Ignore Null)
+
+SQL:
+```sql
+SELECT DIFF(s1), DIFF(s2) from root.test;
+```
+
+Result:
+```
++-----------------------------+------------------+------------------+
+|                         Time|DIFF(root.test.s1)|DIFF(root.test.s2)|
++-----------------------------+------------------+------------------+
+|1970-01-01T08:00:00.001+08:00|              null|              null|
+|1970-01-01T08:00:00.002+08:00|               1.0|              null|
+|1970-01-01T08:00:00.003+08:00|              null|               2.0|
+|1970-01-01T08:00:00.004+08:00|               2.0|              null|
+|1970-01-01T08:00:00.005+08:00|               1.0|               2.0|
+|1970-01-01T08:00:00.006+08:00|              null|               1.0|
++-----------------------------+------------------+------------------+
+```
+
+#### Use `ignoreNull` attribute
+
+SQL:
+```sql
+SELECT DIFF(s1, 'ignoreNull'='false'), DIFF(s2, 'ignoreNull'='false') from root.test;
+```
+
+Result:
+```
++-----------------------------+----------------------------------------+----------------------------------------+
+|                         Time|DIFF(root.test.s1, "ignoreNull"="false")|DIFF(root.test.s2, "ignoreNull"="false")|
++-----------------------------+----------------------------------------+----------------------------------------+
+|1970-01-01T08:00:00.001+08:00|                                    null|                                    null|
+|1970-01-01T08:00:00.002+08:00|                                     1.0|                                    null|
+|1970-01-01T08:00:00.003+08:00|                                    null|                                    null|
+|1970-01-01T08:00:00.004+08:00|                                    null|                                    null|
+|1970-01-01T08:00:00.005+08:00|                                     1.0|                                    null|
+|1970-01-01T08:00:00.006+08:00|                                    null|                                     1.0|
++-----------------------------+----------------------------------------+----------------------------------------+
 ```
\ No newline at end of file
diff --git a/docs/zh/UserGuide/Operators-Functions/Overview.md b/docs/zh/UserGuide/Operators-Functions/Overview.md
index bbcbf0fee1..b0a85dc90e 100644
--- a/docs/zh/UserGuide/Operators-Functions/Overview.md
+++ b/docs/zh/UserGuide/Operators-Functions/Overview.md
@@ -216,6 +216,11 @@ OR, |, ||
 | DERIVATIVE              | INT32 / INT64 / FLOAT / DOUBLE                  | DOUBLE                   | 统计序列中某数据点相对于前一数据点的变化率,数量上等同于 DIFFERENCE /  TIME_DIFFERENCE。范围内第一个数据点没有对应的结果输出。 |
 | NON_NEGATIVE_DERIVATIVE | INT32 / INT64 / FLOAT / DOUBLE                  | DOUBLE                   | 统计序列中某数据点相对于前一数据点的变化率的绝对值,数量上等同于 NON_NEGATIVE_DIFFERENCE /  TIME_DIFFERENCE。范围内第一个数据点没有对应的结果输出。 |
 
+
+| 函数名  | 输入序列类型                         | 参数                                                                                                                     | 输出序列类型 | 功能描述                                           |
+|------|--------------------------------|------------------------------------------------------------------------------------------------------------------------|--------|------------------------------------------------|
+| DIFF | INT32 / INT64 / FLOAT / DOUBLE | `ignoreNull`:可选,默认为true;为true时,前一个数据点值为null时,忽略该数据点继续向前找到第一个出现的不为null的值;为false时,如果前一个数据点为null,则不忽略,使用null进行相减,结果也为null | DOUBLE | 统计序列中某数据点的值与前一数据点的值的差。第一个数据点没有对应的结果输出,输出值为null |
+
 详细说明及示例见文档 [趋势计算函数](./Variation-Trend.md)。
 
 ### 采样函数
diff --git a/docs/zh/UserGuide/Operators-Functions/Variation-Trend.md b/docs/zh/UserGuide/Operators-Functions/Variation-Trend.md
index 04ac9853ac..32e59c5165 100644
--- a/docs/zh/UserGuide/Operators-Functions/Variation-Trend.md
+++ b/docs/zh/UserGuide/Operators-Functions/Variation-Trend.md
@@ -52,3 +52,66 @@ select s1, time_difference(s1), difference(s1), non_negative_difference(s1), der
 Total line number = 5
 It costs 0.014s
 ```
+
+| 函数名  | 输入序列类型                         | 参数                                                                                                                     | 输出序列类型 | 功能描述                                           |
+|------|--------------------------------|------------------------------------------------------------------------------------------------------------------------|--------|------------------------------------------------|
+| DIFF | INT32 / INT64 / FLOAT / DOUBLE | `ignoreNull`:可选,默认为true;为true时,前一个数据点值为null时,忽略该数据点继续向前找到第一个出现的不为null的值;为false时,如果前一个数据点为null,则不忽略,使用null进行相减,结果也为null | DOUBLE | 统计序列中某数据点的值与前一数据点的值的差。第一个数据点没有对应的结果输出,输出值为null |
+
+### 使用示例
+
+#### 原始数据
+
+``` 
++-----------------------------+------------+------------+
+|                         Time|root.test.s1|root.test.s2|
++-----------------------------+------------+------------+
+|1970-01-01T08:00:00.001+08:00|           1|         1.0|
+|1970-01-01T08:00:00.002+08:00|           2|        null|
+|1970-01-01T08:00:00.003+08:00|        null|         3.0|
+|1970-01-01T08:00:00.004+08:00|           4|        null|
+|1970-01-01T08:00:00.005+08:00|           5|         5.0|
+|1970-01-01T08:00:00.006+08:00|        null|         6.0|
++-----------------------------+------------+------------+
+```
+
+#### 不使用ignoreNull参数(忽略null)
+
+SQL:
+```sql
+SELECT DIFF(s1), DIFF(s2) from root.test;
+```
+
+输出:
+```
++-----------------------------+------------------+------------------+
+|                         Time|DIFF(root.test.s1)|DIFF(root.test.s2)|
++-----------------------------+------------------+------------------+
+|1970-01-01T08:00:00.001+08:00|              null|              null|
+|1970-01-01T08:00:00.002+08:00|               1.0|              null|
+|1970-01-01T08:00:00.003+08:00|              null|               2.0|
+|1970-01-01T08:00:00.004+08:00|               2.0|              null|
+|1970-01-01T08:00:00.005+08:00|               1.0|               2.0|
+|1970-01-01T08:00:00.006+08:00|              null|               1.0|
++-----------------------------+------------------+------------------+
+```
+
+#### 使用ignoreNull参数
+
+SQL:
+```sql
+SELECT DIFF(s1, 'ignoreNull'='false'), DIFF(s2, 'ignoreNull'='false') from root.test;
+```
+
+输出:
+```
++-----------------------------+----------------------------------------+----------------------------------------+
+|                         Time|DIFF(root.test.s1, "ignoreNull"="false")|DIFF(root.test.s2, "ignoreNull"="false")|
++-----------------------------+----------------------------------------+----------------------------------------+
+|1970-01-01T08:00:00.001+08:00|                                    null|                                    null|
+|1970-01-01T08:00:00.002+08:00|                                     1.0|                                    null|
+|1970-01-01T08:00:00.003+08:00|                                    null|                                    null|
+|1970-01-01T08:00:00.004+08:00|                                    null|                                    null|
+|1970-01-01T08:00:00.005+08:00|                                     1.0|                                    null|
+|1970-01-01T08:00:00.006+08:00|                                    null|                                     1.0|
++-----------------------------+----------------------------------------+----------------------------------------+
+```
\ No newline at end of file
diff --git a/integration-test/src/main/java/org/apache/iotdb/itbase/constant/TestConstant.java b/integration-test/src/main/java/org/apache/iotdb/itbase/constant/TestConstant.java
index cae3577dde..86fcefc4a0 100644
--- a/integration-test/src/main/java/org/apache/iotdb/itbase/constant/TestConstant.java
+++ b/integration-test/src/main/java/org/apache/iotdb/itbase/constant/TestConstant.java
@@ -45,6 +45,7 @@ public class TestConstant {
   public static final String s5 = "s5";
   public static final String d1 = "root.vehicle.d1";
   public static final String TIMESTAMP_STR = ColumnHeaderConstant.TIME;
+  public static final String DEVICE = ColumnHeaderConstant.DEVICE;
   public static boolean testFlag = true;
   public static String[] stringValue = new String[] {"A", "B", "C", "D", "E"};
   public static String[] booleanValue = new String[] {"true", "false"};
diff --git a/integration-test/src/test/java/org/apache/iotdb/db/it/builtinfunction/scalar/IoTDBDiffFunction2IT.java b/integration-test/src/test/java/org/apache/iotdb/db/it/builtinfunction/scalar/IoTDBDiffFunction2IT.java
new file mode 100644
index 0000000000..d67c1f32ee
--- /dev/null
+++ b/integration-test/src/test/java/org/apache/iotdb/db/it/builtinfunction/scalar/IoTDBDiffFunction2IT.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.iotdb.db.it.builtinfunction.scalar;
+
+import org.apache.iotdb.it.env.EnvFactory;
+import org.apache.iotdb.it.framework.IoTDBTestRunner;
+import org.apache.iotdb.itbase.category.ClusterIT;
+import org.apache.iotdb.itbase.category.LocalStandaloneIT;
+
+import org.junit.BeforeClass;
+import org.junit.experimental.categories.Category;
+import org.junit.runner.RunWith;
+
+import static org.apache.iotdb.db.it.utils.TestUtils.prepareData;
+
+@RunWith(IoTDBTestRunner.class)
+@Category({LocalStandaloneIT.class, ClusterIT.class})
+public class IoTDBDiffFunction2IT extends IoTDBDiffFunctionIT {
+  // 2 devices 2 regions
+  @BeforeClass
+  public static void setUp() throws Exception {
+    EnvFactory.getEnv().getConfig().getCommonConfig().setDataRegionGroupExtensionPolicy("CUSTOM");
+    EnvFactory.getEnv().getConfig().getCommonConfig().setDataRegionGroupPerDatabase(2);
+    EnvFactory.getEnv().getConfig().getCommonConfig().setPartitionInterval(1000);
+    EnvFactory.getEnv().initClusterEnvironment();
+    prepareData(SQLs);
+  }
+}
diff --git a/integration-test/src/test/java/org/apache/iotdb/db/it/builtinfunction/scalar/IoTDBDiffFunction3IT.java b/integration-test/src/test/java/org/apache/iotdb/db/it/builtinfunction/scalar/IoTDBDiffFunction3IT.java
new file mode 100644
index 0000000000..b684791bad
--- /dev/null
+++ b/integration-test/src/test/java/org/apache/iotdb/db/it/builtinfunction/scalar/IoTDBDiffFunction3IT.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.iotdb.db.it.builtinfunction.scalar;
+
+import org.apache.iotdb.it.env.EnvFactory;
+import org.apache.iotdb.it.framework.IoTDBTestRunner;
+import org.apache.iotdb.itbase.category.ClusterIT;
+import org.apache.iotdb.itbase.category.LocalStandaloneIT;
+
+import org.junit.BeforeClass;
+import org.junit.experimental.categories.Category;
+import org.junit.runner.RunWith;
+
+import static org.apache.iotdb.db.it.utils.TestUtils.prepareData;
+
+@RunWith(IoTDBTestRunner.class)
+@Category({LocalStandaloneIT.class, ClusterIT.class})
+public class IoTDBDiffFunction3IT extends IoTDBDiffFunctionIT {
+  // 2 devices 3 regions
+  @BeforeClass
+  public static void setUp() throws Exception {
+    EnvFactory.getEnv().getConfig().getCommonConfig().setDataRegionGroupExtensionPolicy("CUSTOM");
+    EnvFactory.getEnv().getConfig().getCommonConfig().setDataRegionGroupPerDatabase(3);
+    EnvFactory.getEnv().getConfig().getCommonConfig().setPartitionInterval(1000);
+    EnvFactory.getEnv().initClusterEnvironment();
+    prepareData(SQLs);
+  }
+}
diff --git a/integration-test/src/test/java/org/apache/iotdb/db/it/builtinfunction/scalar/IoTDBDiffFunctionIT.java b/integration-test/src/test/java/org/apache/iotdb/db/it/builtinfunction/scalar/IoTDBDiffFunctionIT.java
new file mode 100644
index 0000000000..da613856a4
--- /dev/null
+++ b/integration-test/src/test/java/org/apache/iotdb/db/it/builtinfunction/scalar/IoTDBDiffFunctionIT.java
@@ -0,0 +1,346 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.iotdb.db.it.builtinfunction.scalar;
+
+import org.apache.iotdb.it.env.EnvFactory;
+import org.apache.iotdb.it.framework.IoTDBTestRunner;
+import org.apache.iotdb.itbase.category.ClusterIT;
+import org.apache.iotdb.itbase.category.LocalStandaloneIT;
+
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.runner.RunWith;
+
+import static org.apache.iotdb.db.it.utils.TestUtils.prepareData;
+import static org.apache.iotdb.db.it.utils.TestUtils.resultSetEqualTest;
+import static org.apache.iotdb.itbase.constant.TestConstant.DEVICE;
+import static org.apache.iotdb.itbase.constant.TestConstant.TIMESTAMP_STR;
+
+@RunWith(IoTDBTestRunner.class)
+@Category({LocalStandaloneIT.class, ClusterIT.class})
+public class IoTDBDiffFunctionIT {
+  // 2 devices 4 regions
+  protected static final String[] SQLs =
+      new String[] {
+        "CREATE DATABASE root.db",
+        "CREATE TIMESERIES root.db.d1.s1 WITH DATATYPE=INT32, ENCODING=PLAIN",
+        "CREATE TIMESERIES root.db.d1.s2 WITH DATATYPE=FLOAT, ENCODING=PLAIN",
+        "INSERT INTO root.db.d1(timestamp,s1,s2) values(1, 1, 1)",
+        "INSERT INTO root.db.d1(timestamp,s1) values(2, 2)",
+        "INSERT INTO root.db.d1(timestamp,s2) values(3, 3)",
+        "INSERT INTO root.db.d1(timestamp,s1) values(4, 4)",
+        "INSERT INTO root.db.d1(timestamp,s1,s2) values(5, 5, 5)",
+        "INSERT INTO root.db.d1(timestamp,s2) values(6, 6)",
+        "INSERT INTO root.db.d1(timestamp,s1,s2) values(5000000000, null, 7)",
+        "INSERT INTO root.db.d1(timestamp,s1,s2) values(5000000001, 8, null)",
+        "CREATE TIMESERIES root.db.d2.s1 WITH DATATYPE=INT32, ENCODING=PLAIN",
+        "CREATE TIMESERIES root.db.d2.s2 WITH DATATYPE=FLOAT, ENCODING=PLAIN",
+        "INSERT INTO root.db.d2(timestamp,s1,s2) values(1, 1, 1)",
+        "INSERT INTO root.db.d2(timestamp,s1,s2) values(2, 2, 2)",
+        "INSERT INTO root.db.d2(timestamp,s1,s2) values(5000000000, null, 3)",
+        "INSERT INTO root.db.d2(timestamp,s1,s2) values(5000000001, 4, null)",
+        "flush"
+      };
+
+  @BeforeClass
+  public static void setUp() throws Exception {
+    EnvFactory.getEnv().getConfig().getCommonConfig().setPartitionInterval(1000);
+    EnvFactory.getEnv().initClusterEnvironment();
+    prepareData(SQLs);
+  }
+
+  @AfterClass
+  public static void tearDown() throws Exception {
+    EnvFactory.getEnv().cleanClusterEnvironment();
+  }
+
+  @Test
+  public void testNewTransformerIgnoreNull() {
+    String[] expectedHeader =
+        new String[] {TIMESTAMP_STR, "Diff(root.db.d1.s1)", "diff(root.db.d1.s2)"};
+    String[] retArray =
+        new String[] {
+          "1,null,null,",
+          "2,1.0,null,",
+          "3,null,2.0,",
+          "4,2.0,null,",
+          "5,1.0,2.0,",
+          "6,null,1.0,",
+          "5000000000,null,1.0,",
+          "5000000001,3.0,null,"
+        };
+    resultSetEqualTest("select Diff(s1), diff(s2) from root.db.d1", expectedHeader, retArray);
+
+    // align by device
+    expectedHeader = new String[] {TIMESTAMP_STR, DEVICE, "Diff(s1)", "diff(s2)"};
+    retArray =
+        new String[] {
+          "1,root.db.d1,null,null,",
+          "2,root.db.d1,1.0,null,",
+          "3,root.db.d1,null,2.0,",
+          "4,root.db.d1,2.0,null,",
+          "5,root.db.d1,1.0,2.0,",
+          "6,root.db.d1,null,1.0,",
+          "5000000000,root.db.d1,null,1.0,",
+          "5000000001,root.db.d1,3.0,null,",
+          "1,root.db.d2,null,null,",
+          "2,root.db.d2,1.0,1.0,",
+          "5000000000,root.db.d2,null,1.0,",
+          "5000000001,root.db.d2,2.0,null,"
+        };
+    resultSetEqualTest(
+        "select Diff(s1), diff(s2) from root.db.d1, root.db.d2 align by device",
+        expectedHeader,
+        retArray);
+
+    // align by device + order by time
+    retArray =
+        new String[] {
+          "1,root.db.d1,null,null,",
+          "1,root.db.d2,null,null,",
+          "2,root.db.d1,1.0,null,",
+          "2,root.db.d2,1.0,1.0,",
+          "3,root.db.d1,null,2.0,",
+          "4,root.db.d1,2.0,null,",
+          "5,root.db.d1,1.0,2.0,",
+          "6,root.db.d1,null,1.0,",
+          "5000000000,root.db.d1,null,1.0,",
+          "5000000000,root.db.d2,null,1.0,",
+          "5000000001,root.db.d1,3.0,null,",
+          "5000000001,root.db.d2,2.0,null,"
+        };
+    resultSetEqualTest(
+        "select Diff(s1), diff(s2) from root.db.d1, root.db.d2 order by time align by device",
+        expectedHeader,
+        retArray);
+  }
+
+  @Test
+  public void testNewTransformerRespectNull() {
+    String[] expectedHeader =
+        new String[] {
+          TIMESTAMP_STR,
+          "Diff(root.db.d1.s1, \"ignoreNull\"=\"false\")",
+          "diff(root.db.d1.s2, \"ignoreNull\"=\"false\")"
+        };
+    String[] retArray =
+        new String[] {
+          "1,null,null,",
+          "2,1.0,null,",
+          "3,null,null,",
+          "4,null,null,",
+          "5,1.0,null,",
+          "6,null,1.0,",
+          "5000000000,null,1.0,",
+          "5000000001,null,null,"
+        };
+    resultSetEqualTest(
+        "select Diff(s1, 'ignoreNull'='false'), diff(s2, 'ignoreNull'='false') from root.db.d1",
+        expectedHeader,
+        retArray);
+
+    // align by device
+    expectedHeader =
+        new String[] {
+          TIMESTAMP_STR,
+          DEVICE,
+          "Diff(s1, \"ignoreNull\"=\"false\")",
+          "diff(s2, \"ignoreNull\"=\"false\")"
+        };
+    retArray =
+        new String[] {
+          "1,root.db.d1,null,null,",
+          "2,root.db.d1,1.0,null,",
+          "3,root.db.d1,null,null,",
+          "4,root.db.d1,null,null,",
+          "5,root.db.d1,1.0,null,",
+          "6,root.db.d1,null,1.0,",
+          "5000000000,root.db.d1,null,1.0,",
+          "5000000001,root.db.d1,null,null,",
+          "1,root.db.d2,null,null,",
+          "2,root.db.d2,1.0,1.0,",
+          "5000000000,root.db.d2,null,1.0,",
+          "5000000001,root.db.d2,null,null,",
+        };
+    resultSetEqualTest(
+        "select Diff(s1, 'ignoreNull'='false'), diff(s2, 'ignoreNull'='false') from root.db.d1, root.db.d2 align by device",
+        expectedHeader,
+        retArray);
+
+    // align by device + order by time
+    retArray =
+        new String[] {
+          "1,root.db.d1,null,null,",
+          "1,root.db.d2,null,null,",
+          "2,root.db.d1,1.0,null,",
+          "2,root.db.d2,1.0,1.0,",
+          "3,root.db.d1,null,null,",
+          "4,root.db.d1,null,null,",
+          "5,root.db.d1,1.0,null,",
+          "6,root.db.d1,null,1.0,",
+          "5000000000,root.db.d1,null,1.0,",
+          "5000000000,root.db.d2,null,1.0,",
+          "5000000001,root.db.d1,null,null,",
+          "5000000001,root.db.d2,null,null,",
+        };
+    resultSetEqualTest(
+        "select Diff(s1, 'ignoreNull'='false'), diff(s2, 'ignoreNull'='false') from root.db.d1, root.db.d2 order by time align by device",
+        expectedHeader,
+        retArray);
+  }
+
+  // [change_points] is not mappable function, so this calculation use old transformer
+  @Test
+  public void testOldTransformerIgnoreNull() {
+    String[] expectedHeader =
+        new String[] {TIMESTAMP_STR, "change_points(root.db.d1.s1)", "diff(root.db.d1.s2)"};
+    String[] retArray =
+        new String[] {
+          "1,1,null,",
+          "2,2,null,",
+          "3,null,2.0,",
+          "4,4,null,",
+          "5,5,2.0,",
+          "6,null,1.0,",
+          "5000000000,null,1.0,",
+          "5000000001,8,null,"
+        };
+    resultSetEqualTest(
+        "select change_points(s1), diff(s2) from root.db.d1", expectedHeader, retArray);
+
+    // align by device
+    expectedHeader = new String[] {TIMESTAMP_STR, DEVICE, "change_points(s1)", "diff(s2)"};
+    retArray =
+        new String[] {
+          "1,root.db.d1,1,null,",
+          "2,root.db.d1,2,null,",
+          "3,root.db.d1,null,2.0,",
+          "4,root.db.d1,4,null,",
+          "5,root.db.d1,5,2.0,",
+          "6,root.db.d1,null,1.0,",
+          "5000000000,root.db.d1,null,1.0,",
+          "5000000001,root.db.d1,8,null,",
+          "1,root.db.d2,1,null,",
+          "2,root.db.d2,2,1.0,",
+          "5000000000,root.db.d2,null,1.0,",
+          "5000000001,root.db.d2,4,null,",
+        };
+    resultSetEqualTest(
+        "select change_points(s1), diff(s2) from root.db.d1, root.db.d2 align by device",
+        expectedHeader,
+        retArray);
+
+    // align by device + order by time
+    expectedHeader = new String[] {TIMESTAMP_STR, DEVICE, "change_points(s1)", "diff(s2)"};
+    retArray =
+        new String[] {
+          "1,root.db.d1,1,null,",
+          "1,root.db.d2,1,null,",
+          "2,root.db.d1,2,null,",
+          "2,root.db.d2,2,1.0,",
+          "3,root.db.d1,null,2.0,",
+          "4,root.db.d1,4,null,",
+          "5,root.db.d1,5,2.0,",
+          "6,root.db.d1,null,1.0,",
+          "5000000000,root.db.d1,null,1.0,",
+          "5000000000,root.db.d2,null,1.0,",
+          "5000000001,root.db.d1,8,null,",
+          "5000000001,root.db.d2,4,null,",
+        };
+    resultSetEqualTest(
+        "select change_points(s1), diff(s2) from root.db.d1, root.db.d2 order by time align by device",
+        expectedHeader,
+        retArray);
+  }
+
+  @Test
+  public void testOldTransformerRespectNull() {
+    String[] expectedHeader =
+        new String[] {
+          TIMESTAMP_STR,
+          "change_points(root.db.d1.s1)",
+          "diff(root.db.d1.s2, \"ignoreNull\"=\"false\")"
+        };
+    String[] retArray =
+        new String[] {
+          "1,1,null,",
+          "2,2,null,",
+          "4,4,null,",
+          "5,5,null,",
+          "6,null,1.0,",
+          "5000000000,null,1.0,",
+          "5000000001,8,null,"
+        };
+    resultSetEqualTest(
+        "select change_points(s1), diff(s2, 'ignoreNull'='false') from root.db.d1",
+        expectedHeader,
+        retArray);
+
+    // align by device
+    expectedHeader =
+        new String[] {
+          TIMESTAMP_STR, DEVICE, "change_points(s1)", "diff(s2, \"ignoreNull\"=\"false\")"
+        };
+    retArray =
+        new String[] {
+          "1,root.db.d1,1,null,",
+          "2,root.db.d1,2,null,",
+          "4,root.db.d1,4,null,",
+          "5,root.db.d1,5,null,",
+          "6,root.db.d1,null,1.0,",
+          "5000000000,root.db.d1,null,1.0,",
+          "5000000001,root.db.d1,8,null,",
+          "1,root.db.d2,1,null,",
+          "2,root.db.d2,2,1.0,",
+          "5000000000,root.db.d2,null,1.0,",
+          "5000000001,root.db.d2,4,null,",
+        };
+    resultSetEqualTest(
+        "select change_points(s1), diff(s2, 'ignoreNull'='false') from root.db.d1, root.db.d2 align by device",
+        expectedHeader,
+        retArray);
+
+    // align by device + order by time
+    expectedHeader =
+        new String[] {
+          TIMESTAMP_STR, DEVICE, "change_points(s1)", "diff(s2, \"ignoreNull\"=\"false\")"
+        };
+    retArray =
+        new String[] {
+          "1,root.db.d1,1,null,",
+          "1,root.db.d2,1,null,",
+          "2,root.db.d1,2,null,",
+          "2,root.db.d2,2,1.0,",
+          "4,root.db.d1,4,null,",
+          "5,root.db.d1,5,null,",
+          "6,root.db.d1,null,1.0,",
+          "5000000000,root.db.d1,null,1.0,",
+          "5000000000,root.db.d2,null,1.0,",
+          "5000000001,root.db.d1,8,null,",
+          "5000000001,root.db.d2,4,null,",
+        };
+    resultSetEqualTest(
+        "select change_points(s1), diff(s2, 'ignoreNull'='false') from root.db.d1, root.db.d2 order by time align by device",
+        expectedHeader,
+        retArray);
+  }
+}
diff --git a/node-commons/src/main/java/org/apache/iotdb/commons/udf/builtin/BuiltinScalarFunction.java b/node-commons/src/main/java/org/apache/iotdb/commons/udf/builtin/BuiltinScalarFunction.java
new file mode 100644
index 0000000000..24bc734400
--- /dev/null
+++ b/node-commons/src/main/java/org/apache/iotdb/commons/udf/builtin/BuiltinScalarFunction.java
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.iotdb.commons.udf.builtin;
+
+import com.google.common.collect.ImmutableSet;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+public enum BuiltinScalarFunction {
+  DIFF("diff"),
+  ;
+
+  private final String functionName;
+
+  BuiltinScalarFunction(String functionName) {
+    this.functionName = functionName;
+  }
+
+  public String getFunctionName() {
+    return functionName;
+  }
+
+  private static final Set<String> NATIVE_FUNCTION_NAMES =
+      new HashSet<>(
+          Arrays.stream(BuiltinScalarFunction.values())
+              .map(BuiltinScalarFunction::getFunctionName)
+              .collect(Collectors.toList()));
+
+  /**
+   * We shouldn't apply these functions to each DataRegion for one device, because these functions
+   * need all data to calculate correct result. So we need to collect all data for one device in one
+   * DataRegion, and then apply these functions to only that one DataRegion.
+   */
+  public static final Set<String> DEVICE_VIEW_SPECIAL_PROCESS_FUNCTIONS = ImmutableSet.of("diff");
+
+  public static Set<String> getNativeFunctionNames() {
+    return NATIVE_FUNCTION_NAMES;
+  }
+}
diff --git a/server/src/main/java/org/apache/iotdb/db/constant/SqlConstant.java b/server/src/main/java/org/apache/iotdb/db/constant/SqlConstant.java
index b41481d739..1861d98eb7 100644
--- a/server/src/main/java/org/apache/iotdb/db/constant/SqlConstant.java
+++ b/server/src/main/java/org/apache/iotdb/db/constant/SqlConstant.java
@@ -54,6 +54,9 @@ public class SqlConstant {
   public static final String AVG = "avg";
   public static final String SUM = "sum";
 
+  // names of scalar functions
+  public static final String DIFF = "diff";
+
   public static final String LAST = "last";
 
   public static String[] getSingleRootArray() {
diff --git a/server/src/main/java/org/apache/iotdb/db/mpp/plan/analyze/Analysis.java b/server/src/main/java/org/apache/iotdb/db/mpp/plan/analyze/Analysis.java
index 92f9018ca5..123f4a7a35 100644
--- a/server/src/main/java/org/apache/iotdb/db/mpp/plan/analyze/Analysis.java
+++ b/server/src/main/java/org/apache/iotdb/db/mpp/plan/analyze/Analysis.java
@@ -137,6 +137,10 @@ public class Analysis {
 
   private Set<Expression> deviceViewOutputExpressions;
 
+  // indicates whether DeviceView need special process when rewriteSource in DistributionPlan,
+  // you can see SourceRewriter#visitDeviceView to get more information
+  private boolean deviceViewSpecialProcess;
+
   /////////////////////////////////////////////////////////////////////////////////////////////////
   // Query Common Analysis (above DeviceView)
   /////////////////////////////////////////////////////////////////////////////////////////////////
@@ -482,6 +486,14 @@ public class Analysis {
     this.deviceViewOutputExpressions = deviceViewOutputExpressions;
   }
 
+  public boolean isDeviceViewSpecialProcess() {
+    return deviceViewSpecialProcess;
+  }
+
+  public void setDeviceViewSpecialProcess(boolean deviceViewSpecialProcess) {
+    this.deviceViewSpecialProcess = deviceViewSpecialProcess;
+  }
+
   public DeviceViewIntoPathDescriptor getDeviceViewIntoPathDescriptor() {
     return deviceViewIntoPathDescriptor;
   }
diff --git a/server/src/main/java/org/apache/iotdb/db/mpp/plan/analyze/AnalyzeVisitor.java b/server/src/main/java/org/apache/iotdb/db/mpp/plan/analyze/AnalyzeVisitor.java
index ed4dd96898..0621dd3a81 100644
--- a/server/src/main/java/org/apache/iotdb/db/mpp/plan/analyze/AnalyzeVisitor.java
+++ b/server/src/main/java/org/apache/iotdb/db/mpp/plan/analyze/AnalyzeVisitor.java
@@ -1060,6 +1060,24 @@ public class AnalyzeVisitor extends StatementVisitor<Analysis, MPPQueryContext>
       deviceViewInputIndexesMap.put(deviceName, indexes);
     }
     analysis.setDeviceViewInputIndexesMap(deviceViewInputIndexesMap);
+    analysis.setDeviceViewSpecialProcess(
+        analyzeDeviceViewSpecialProcess(deviceViewOutputExpressions, queryStatement));
+  }
+
+  private boolean analyzeDeviceViewSpecialProcess(
+      Set<Expression> deviceViewOutputExpressions, QueryStatement queryStatement) {
+    if (queryStatement.isAggregationQuery()
+        || queryStatement.hasWhere()
+            && ExpressionAnalyzer.isDeviceViewNeedSpecialProcess(
+                queryStatement.getWhereCondition().getPredicate())) {
+      return true;
+    }
+    for (Expression expression : deviceViewOutputExpressions) {
+      if (ExpressionAnalyzer.isDeviceViewNeedSpecialProcess(expression)) {
+        return true;
+      }
+    }
+    return false;
   }
 
   private void analyzeOutput(
diff --git a/server/src/main/java/org/apache/iotdb/db/mpp/plan/analyze/ExpressionAnalyzer.java b/server/src/main/java/org/apache/iotdb/db/mpp/plan/analyze/ExpressionAnalyzer.java
index 3f2b3617bd..3cbafc4948 100644
--- a/server/src/main/java/org/apache/iotdb/db/mpp/plan/analyze/ExpressionAnalyzer.java
+++ b/server/src/main/java/org/apache/iotdb/db/mpp/plan/analyze/ExpressionAnalyzer.java
@@ -24,6 +24,7 @@ import org.apache.iotdb.commons.exception.IllegalPathException;
 import org.apache.iotdb.commons.path.MeasurementPath;
 import org.apache.iotdb.commons.path.PartialPath;
 import org.apache.iotdb.commons.path.PathPatternTree;
+import org.apache.iotdb.commons.udf.builtin.BuiltinScalarFunction;
 import org.apache.iotdb.db.constant.SqlConstant;
 import org.apache.iotdb.db.exception.sql.SemanticException;
 import org.apache.iotdb.db.mpp.common.header.ColumnHeader;
@@ -1267,4 +1268,36 @@ public class ExpressionAnalyzer {
           "unsupported expression type: " + predicate.getExpressionType());
     }
   }
+
+  public static boolean isDeviceViewNeedSpecialProcess(Expression expression) {
+    if (expression instanceof TernaryExpression) {
+      TernaryExpression ternaryExpression = (TernaryExpression) expression;
+      return isDeviceViewNeedSpecialProcess(ternaryExpression.getFirstExpression())
+          || isDeviceViewNeedSpecialProcess(ternaryExpression.getSecondExpression())
+          || isDeviceViewNeedSpecialProcess(ternaryExpression.getThirdExpression());
+    } else if (expression instanceof BinaryExpression) {
+      BinaryExpression binaryExpression = (BinaryExpression) expression;
+      return isDeviceViewNeedSpecialProcess(binaryExpression.getLeftExpression())
+          || isDeviceViewNeedSpecialProcess(binaryExpression.getRightExpression());
+    } else if (expression instanceof UnaryExpression) {
+      return isDeviceViewNeedSpecialProcess(((UnaryExpression) expression).getExpression());
+    } else if (expression instanceof FunctionExpression) {
+      if (((FunctionExpression) expression).isBuiltInScalarFunction()
+          && BuiltinScalarFunction.DEVICE_VIEW_SPECIAL_PROCESS_FUNCTIONS.contains(
+              ((FunctionExpression) expression).getFunctionName().toLowerCase())) {
+        return true;
+      }
+      for (Expression child : expression.getExpressions()) {
+        if (isDeviceViewNeedSpecialProcess(child)) {
+          return true;
+        }
+      }
+      return false;
+    } else if (expression instanceof LeafOperand) {
+      return false;
+    } else {
+      throw new IllegalArgumentException(
+          "unsupported expression type: " + expression.getExpressionType());
+    }
+  }
 }
diff --git a/server/src/main/java/org/apache/iotdb/db/mpp/plan/analyze/ExpressionTypeAnalyzer.java b/server/src/main/java/org/apache/iotdb/db/mpp/plan/analyze/ExpressionTypeAnalyzer.java
index 145b8e92b5..e7d841766c 100644
--- a/server/src/main/java/org/apache/iotdb/db/mpp/plan/analyze/ExpressionTypeAnalyzer.java
+++ b/server/src/main/java/org/apache/iotdb/db/mpp/plan/analyze/ExpressionTypeAnalyzer.java
@@ -255,6 +255,13 @@ public class ExpressionTypeAnalyzer {
             TypeInferenceUtils.getAggrDataType(
                 functionExpression.getFunctionName(),
                 expressionTypes.get(NodeRef.of(inputExpressions.get(0)))));
+      }
+      if (functionExpression.isBuiltInScalarFunction()) {
+        return setExpressionType(
+            functionExpression,
+            TypeInferenceUtils.getScalarFunctionDataType(
+                functionExpression.getFunctionName(),
+                expressionTypes.get(NodeRef.of(inputExpressions.get(0)))));
       } else {
         return setExpressionType(
             functionExpression,
diff --git a/server/src/main/java/org/apache/iotdb/db/mpp/plan/expression/multi/FunctionExpression.java b/server/src/main/java/org/apache/iotdb/db/mpp/plan/expression/multi/FunctionExpression.java
index 3e30eb7e34..66b458ef68 100644
--- a/server/src/main/java/org/apache/iotdb/db/mpp/plan/expression/multi/FunctionExpression.java
+++ b/server/src/main/java/org/apache/iotdb/db/mpp/plan/expression/multi/FunctionExpression.java
@@ -22,6 +22,7 @@ package org.apache.iotdb.db.mpp.plan.expression.multi;
 import org.apache.iotdb.commons.conf.IoTDBConstant;
 import org.apache.iotdb.commons.path.PartialPath;
 import org.apache.iotdb.commons.udf.builtin.BuiltinAggregationFunction;
+import org.apache.iotdb.commons.udf.builtin.BuiltinScalarFunction;
 import org.apache.iotdb.db.mpp.common.NodeRef;
 import org.apache.iotdb.db.mpp.plan.expression.Expression;
 import org.apache.iotdb.db.mpp.plan.expression.ExpressionType;
@@ -55,6 +56,8 @@ public class FunctionExpression extends Expression {
    */
   private Boolean isBuiltInAggregationFunctionExpressionCache;
 
+  private Boolean isBuiltInScalarFunctionCache;
+
   private final String functionName;
   private final LinkedHashMap<String, String> functionAttributes;
 
@@ -110,6 +113,14 @@ public class FunctionExpression extends Expression {
     return isBuiltInAggregationFunctionExpressionCache;
   }
 
+  public Boolean isBuiltInScalarFunction() {
+    if (isBuiltInScalarFunctionCache == null) {
+      isBuiltInScalarFunctionCache =
+          BuiltinScalarFunction.getNativeFunctionNames().contains(functionName.toLowerCase());
+    }
+    return isBuiltInScalarFunctionCache;
+  }
+
   @Override
   public boolean isConstantOperandInternal() {
     if (isConstantOperandCache == null) {
@@ -197,7 +208,7 @@ public class FunctionExpression extends Expression {
 
   @Override
   public boolean isMappable(Map<NodeRef<Expression>, TSDataType> expressionTypes) {
-    if (isBuiltInAggregationFunctionExpression()) {
+    if (isBuiltInAggregationFunctionExpression() || isBuiltInScalarFunction()) {
       return true;
     }
     return new UDTFInformationInferrer(functionName)
diff --git a/server/src/main/java/org/apache/iotdb/db/mpp/plan/expression/visitor/ColumnTransformerVisitor.java b/server/src/main/java/org/apache/iotdb/db/mpp/plan/expression/visitor/ColumnTransformerVisitor.java
index b2d3add5fa..3c46c36e5b 100644
--- a/server/src/main/java/org/apache/iotdb/db/mpp/plan/expression/visitor/ColumnTransformerVisitor.java
+++ b/server/src/main/java/org/apache/iotdb/db/mpp/plan/expression/visitor/ColumnTransformerVisitor.java
@@ -19,6 +19,7 @@
 
 package org.apache.iotdb.db.mpp.plan.expression.visitor;
 
+import org.apache.iotdb.db.constant.SqlConstant;
 import org.apache.iotdb.db.mpp.common.NodeRef;
 import org.apache.iotdb.db.mpp.plan.expression.Expression;
 import org.apache.iotdb.db.mpp.plan.expression.binary.BinaryExpression;
@@ -57,6 +58,7 @@ import org.apache.iotdb.db.mpp.transformation.dag.column.leaf.TimeColumnTransfor
 import org.apache.iotdb.db.mpp.transformation.dag.column.multi.MappableUDFColumnTransformer;
 import org.apache.iotdb.db.mpp.transformation.dag.column.ternary.BetweenColumnTransformer;
 import org.apache.iotdb.db.mpp.transformation.dag.column.unary.ArithmeticNegationColumnTransformer;
+import org.apache.iotdb.db.mpp.transformation.dag.column.unary.DiffFunctionColumnTransformer;
 import org.apache.iotdb.db.mpp.transformation.dag.column.unary.InColumnTransformer;
 import org.apache.iotdb.db.mpp.transformation.dag.column.unary.IsNullColumnTransformer;
 import org.apache.iotdb.db.mpp.transformation.dag.column.unary.LogicNotColumnTransformer;
@@ -218,6 +220,9 @@ public class ColumnTransformerVisitor
                       .getValueColumnIndex());
           context.leafList.add(identity);
           context.cache.put(functionExpression, identity);
+        } else if (functionExpression.isBuiltInScalarFunction()) {
+          context.cache.put(
+              functionExpression, getBuiltInScalarFunctionTransformer(functionExpression, context));
         } else {
           ColumnTransformer[] inputColumnTransformers =
               expressions.stream()
@@ -254,6 +259,24 @@ public class ColumnTransformerVisitor
     return res;
   }
 
+  private ColumnTransformer getBuiltInScalarFunctionTransformer(
+      FunctionExpression expression, ColumnTransformerVisitorContext context) {
+    ColumnTransformer childColumnTransformer =
+        this.process(expression.getExpressions().get(0), context);
+
+    switch (expression.getFunctionName()) {
+      case SqlConstant.DIFF:
+        return new DiffFunctionColumnTransformer(
+            TypeFactory.getType(TSDataType.DOUBLE),
+            childColumnTransformer,
+            Boolean.parseBoolean(
+                expression.getFunctionAttributes().getOrDefault("ignoreNull", "true")));
+      default:
+        throw new IllegalArgumentException(
+            "Invalid Scalar function: " + expression.getExpressionString());
+    }
+  }
+
   @Override
   public ColumnTransformer visitTimeStampOperand(
       TimestampOperand timestampOperand, ColumnTransformerVisitorContext context) {
diff --git a/server/src/main/java/org/apache/iotdb/db/mpp/plan/expression/visitor/IntermediateLayerVisitor.java b/server/src/main/java/org/apache/iotdb/db/mpp/plan/expression/visitor/IntermediateLayerVisitor.java
index 71d6a1ddf6..5839fa5217 100644
--- a/server/src/main/java/org/apache/iotdb/db/mpp/plan/expression/visitor/IntermediateLayerVisitor.java
+++ b/server/src/main/java/org/apache/iotdb/db/mpp/plan/expression/visitor/IntermediateLayerVisitor.java
@@ -19,6 +19,7 @@
 
 package org.apache.iotdb.db.mpp.plan.expression.visitor;
 
+import org.apache.iotdb.db.constant.SqlConstant;
 import org.apache.iotdb.db.exception.query.QueryProcessException;
 import org.apache.iotdb.db.mpp.common.NodeRef;
 import org.apache.iotdb.db.mpp.plan.expression.Expression;
@@ -62,6 +63,7 @@ import org.apache.iotdb.db.mpp.transformation.dag.transformer.multi.UDFQueryRowW
 import org.apache.iotdb.db.mpp.transformation.dag.transformer.multi.UDFQueryTransformer;
 import org.apache.iotdb.db.mpp.transformation.dag.transformer.ternary.BetweenTransformer;
 import org.apache.iotdb.db.mpp.transformation.dag.transformer.unary.ArithmeticNegationTransformer;
+import org.apache.iotdb.db.mpp.transformation.dag.transformer.unary.DiffFunctionTransformer;
 import org.apache.iotdb.db.mpp.transformation.dag.transformer.unary.InTransformer;
 import org.apache.iotdb.db.mpp.transformation.dag.transformer.unary.IsNullTransformer;
 import org.apache.iotdb.db.mpp.transformation.dag.transformer.unary.LogicNotTransformer;
@@ -198,6 +200,8 @@ public class IntermediateLayerVisitor
             new TransparentTransformer(
                 context.rawTimeSeriesInputLayer.constructValuePointReader(
                     functionExpression.getInputColumnIndex()));
+      } else if (functionExpression.isBuiltInScalarFunction()) {
+        transformer = getBuiltInScalarFunctionTransformer(functionExpression, context);
       } else {
         try {
           IntermediateLayer udfInputIntermediateLayer =
@@ -219,6 +223,24 @@ public class IntermediateLayerVisitor
     return context.expressionIntermediateLayerMap.get(functionExpression);
   }
 
+  private Transformer getBuiltInScalarFunctionTransformer(
+      FunctionExpression expression, IntermediateLayerVisitorContext context) {
+
+    LayerPointReader childPointReader =
+        this.process(expression.getExpressions().get(0), context).constructPointReader();
+
+    switch (expression.getFunctionName()) {
+      case SqlConstant.DIFF:
+        return new DiffFunctionTransformer(
+            childPointReader,
+            Boolean.parseBoolean(
+                expression.getFunctionAttributes().getOrDefault("ignoreNull", "true")));
+      default:
+        throw new IllegalArgumentException(
+            "Invalid Scalar function: " + expression.getExpressionString());
+    }
+  }
+
   @Override
   public IntermediateLayer visitTimeStampOperand(
       TimestampOperand timestampOperand, IntermediateLayerVisitorContext context) {
diff --git a/server/src/main/java/org/apache/iotdb/db/mpp/plan/planner/distribution/SourceRewriter.java b/server/src/main/java/org/apache/iotdb/db/mpp/plan/planner/distribution/SourceRewriter.java
index 5ae25d5b7f..f8db8163a4 100644
--- a/server/src/main/java/org/apache/iotdb/db/mpp/plan/planner/distribution/SourceRewriter.java
+++ b/server/src/main/java/org/apache/iotdb/db/mpp/plan/planner/distribution/SourceRewriter.java
@@ -110,7 +110,8 @@ public class SourceRewriter extends SimplePlanNodeRewriter<DistributionPlanConte
   public List<PlanNode> visitSingleDeviceView(
       SingleDeviceViewNode node, DistributionPlanContext context) {
 
-    if (isAggregationQuery()) {
+    // Same process logic as visitDeviceView
+    if (analysis.isDeviceViewSpecialProcess()) {
       List<PlanNode> rewroteChildren = rewrite(node.getChild(), context);
       if (rewroteChildren.size() != 1) {
         throw new IllegalStateException("SingleDeviceViewNode have only one child");
@@ -152,10 +153,11 @@ public class SourceRewriter extends SimplePlanNodeRewriter<DistributionPlanConte
         node.getDevices().size() == node.getChildren().size(),
         "size of devices and its children in DeviceViewNode should be same");
 
-    // If the logicalPlan is mixed by DeviceView and Aggregation, it should be processed by a
-    // special logic.
-    if (isAggregationQuery()) {
-      return processDeviceViewWithAggregation(node, context);
+    // If the DeviceView is mixed with Function that need to merge data from different Data Region,
+    // it should be processed by a special logic.
+    // Now the Functions are : all Aggregation Functions and DIFF
+    if (analysis.isDeviceViewSpecialProcess()) {
+      return processSpecialDeviceView(node, context);
     }
 
     Set<TRegionReplicaSet> relatedDataRegions = new HashSet<>();
@@ -204,7 +206,7 @@ public class SourceRewriter extends SimplePlanNodeRewriter<DistributionPlanConte
     return Collections.singletonList(mergeSortNode);
   }
 
-  private List<PlanNode> processDeviceViewWithAggregation(
+  private List<PlanNode> processSpecialDeviceView(
       DeviceViewNode node, DistributionPlanContext context) {
     DeviceViewNode newRoot = cloneDeviceViewNodeWithoutChild(node, context);
     for (int i = 0; i < node.getDevices().size(); i++) {
diff --git a/server/src/main/java/org/apache/iotdb/db/mpp/transformation/dag/column/unary/DiffFunctionColumnTransformer.java b/server/src/main/java/org/apache/iotdb/db/mpp/transformation/dag/column/unary/DiffFunctionColumnTransformer.java
new file mode 100644
index 0000000000..2128c5cd6c
--- /dev/null
+++ b/server/src/main/java/org/apache/iotdb/db/mpp/transformation/dag/column/unary/DiffFunctionColumnTransformer.java
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.iotdb.db.mpp.transformation.dag.column.unary;
+
+import org.apache.iotdb.db.mpp.transformation.dag.column.ColumnTransformer;
+import org.apache.iotdb.tsfile.read.common.block.column.Column;
+import org.apache.iotdb.tsfile.read.common.block.column.ColumnBuilder;
+import org.apache.iotdb.tsfile.read.common.type.Type;
+
+public class DiffFunctionColumnTransformer extends UnaryColumnTransformer {
+
+  // default is true
+  private final boolean ignoreNull;
+
+  // cache the last non-null value
+  private double lastValue;
+
+  // indicate whether lastValue is null
+  private boolean lastValueIsNull = true;
+
+  public DiffFunctionColumnTransformer(
+      Type returnType, ColumnTransformer childColumnTransformer, boolean ignoreNull) {
+    super(returnType, childColumnTransformer);
+    this.ignoreNull = ignoreNull;
+  }
+
+  @Override
+  protected void doTransform(Column column, ColumnBuilder columnBuilder) {
+    for (int i = 0, n = column.getPositionCount(); i < n; i++) {
+      if (column.isNull(i)) {
+        columnBuilder.appendNull(); // currValue is null, append null
+
+        // When currValue is null:
+        // ignoreNull = true, keep lastValueIsNull as before
+        // ignoreNull = false, update lastValueIsNull to true
+        lastValueIsNull |= !ignoreNull;
+      } else {
+        double currValue = childColumnTransformer.getType().getDouble(column, i);
+        if (lastValueIsNull) {
+          columnBuilder.appendNull(); // lastValue is null, append null
+        } else {
+          returnType.writeDouble(columnBuilder, currValue - lastValue);
+        }
+
+        lastValue = currValue; // currValue is not null, update lastValue
+        lastValueIsNull = false;
+      }
+    }
+  }
+}
diff --git a/server/src/main/java/org/apache/iotdb/db/mpp/transformation/dag/transformer/unary/DiffFunctionTransformer.java b/server/src/main/java/org/apache/iotdb/db/mpp/transformation/dag/transformer/unary/DiffFunctionTransformer.java
new file mode 100644
index 0000000000..8ed9b02c9d
--- /dev/null
+++ b/server/src/main/java/org/apache/iotdb/db/mpp/transformation/dag/transformer/unary/DiffFunctionTransformer.java
@@ -0,0 +1,103 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.iotdb.db.mpp.transformation.dag.transformer.unary;
+
+import org.apache.iotdb.db.exception.query.QueryProcessException;
+import org.apache.iotdb.db.mpp.transformation.api.LayerPointReader;
+import org.apache.iotdb.db.mpp.transformation.api.YieldableState;
+import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType;
+
+import java.io.IOException;
+
+public class DiffFunctionTransformer extends UnaryTransformer {
+  private final boolean ignoreNull;
+
+  // cache the last non-null value
+  private double lastValue;
+
+  // indicate whether lastValue is null
+  private boolean lastValueIsNull = true;
+
+  public DiffFunctionTransformer(LayerPointReader layerPointReader, boolean ignoreNull) {
+    super(layerPointReader);
+    this.ignoreNull = ignoreNull;
+  }
+
+  @Override
+  public TSDataType getDataType() {
+    return TSDataType.DOUBLE;
+  }
+
+  @Override
+  public final YieldableState yieldValue() throws IOException, QueryProcessException {
+    final YieldableState yieldableState = layerPointReader.yield();
+    if (!YieldableState.YIELDABLE.equals(yieldableState)) {
+      return yieldableState;
+    }
+
+    if (!isLayerPointReaderConstant) {
+      cachedTime = layerPointReader.currentTime();
+    }
+
+    transformAndCache();
+
+    layerPointReader.readyForNext();
+    return YieldableState.YIELDABLE;
+  }
+
+  @Override
+  protected void transformAndCache() throws QueryProcessException, IOException {
+    if (layerPointReader.isCurrentNull()) {
+      currentNull = true; // currValue is null, append null
+
+      // When currValue is null:
+      // ignoreNull = true, keep lastValueIsNull as before
+      // ignoreNull = false, update lastValueIsNull to true
+      lastValueIsNull |= !ignoreNull;
+    } else {
+      double currValue;
+      switch (layerPointReaderDataType) {
+        case INT32:
+          currValue = layerPointReader.currentInt();
+          break;
+        case INT64:
+          currValue = layerPointReader.currentLong();
+          break;
+        case FLOAT:
+          currValue = layerPointReader.currentFloat();
+          break;
+        case DOUBLE:
+          currValue = layerPointReader.currentDouble();
+          break;
+        default:
+          throw new QueryProcessException(
+              "Unsupported data type: " + layerPointReader.getDataType().toString());
+      }
+      if (lastValueIsNull) {
+        currentNull = true; // lastValue is null, append null
+      } else {
+        cachedDouble = currValue - lastValue;
+      }
+
+      lastValue = currValue; // currValue is not null, update lastValue
+      lastValueIsNull = false;
+    }
+  }
+}
diff --git a/server/src/main/java/org/apache/iotdb/db/utils/TypeInferenceUtils.java b/server/src/main/java/org/apache/iotdb/db/utils/TypeInferenceUtils.java
index 4d23b58904..e7b37506fc 100644
--- a/server/src/main/java/org/apache/iotdb/db/utils/TypeInferenceUtils.java
+++ b/server/src/main/java/org/apache/iotdb/db/utils/TypeInferenceUtils.java
@@ -158,6 +158,35 @@ public class TypeInferenceUtils {
     }
   }
 
+  public static TSDataType getScalarFunctionDataType(String funcName, TSDataType dataType) {
+    if (funcName == null) {
+      throw new IllegalArgumentException("ScalarFunction Name must not be null");
+    }
+    verifyIsScalarFunctionDataTypeMatched(funcName, dataType);
+
+    switch (funcName.toLowerCase()) {
+      case SqlConstant.DIFF:
+        return TSDataType.DOUBLE;
+      default:
+        throw new IllegalArgumentException("Invalid Scalar function: " + funcName);
+    }
+  }
+
+  private static void verifyIsScalarFunctionDataTypeMatched(String funcName, TSDataType dataType) {
+    switch (funcName.toLowerCase()) {
+      case SqlConstant.DIFF:
+        if (dataType.isNumeric()) {
+          return;
+        }
+        throw new SemanticException(
+            String.format(
+                "Scalar function [%s] only support numeric data types [INT32, INT64, FLOAT, DOUBLE]",
+                funcName));
+      default:
+        throw new IllegalArgumentException("Invalid Scalar function: " + funcName);
+    }
+  }
+
   public static boolean canAutoCast(TSDataType fromType, TSDataType toType) {
     if (fromType.equals(toType)) {
       return true;
diff --git a/server/src/test/java/org/apache/iotdb/db/mpp/plan/plan/distribution/AlignedByDeviceTest.java b/server/src/test/java/org/apache/iotdb/db/mpp/plan/plan/distribution/AlignedByDeviceTest.java
index af64fc39bb..5d1002e505 100644
--- a/server/src/test/java/org/apache/iotdb/db/mpp/plan/plan/distribution/AlignedByDeviceTest.java
+++ b/server/src/test/java/org/apache/iotdb/db/mpp/plan/plan/distribution/AlignedByDeviceTest.java
@@ -19,17 +19,125 @@
 
 package org.apache.iotdb.db.mpp.plan.plan.distribution;
 
+import org.apache.iotdb.common.rpc.thrift.TEndPoint;
+import org.apache.iotdb.db.mpp.common.MPPQueryContext;
+import org.apache.iotdb.db.mpp.common.QueryId;
+import org.apache.iotdb.db.mpp.plan.analyze.Analysis;
+import org.apache.iotdb.db.mpp.plan.planner.distribution.DistributionPlanner;
+import org.apache.iotdb.db.mpp.plan.planner.plan.DistributedQueryPlan;
 import org.apache.iotdb.db.mpp.plan.planner.plan.LogicalQueryPlan;
+import org.apache.iotdb.db.mpp.plan.planner.plan.node.PlanNode;
+import org.apache.iotdb.db.mpp.plan.planner.plan.node.process.DeviceViewNode;
+import org.apache.iotdb.db.mpp.plan.planner.plan.node.process.ExchangeNode;
+import org.apache.iotdb.db.mpp.plan.planner.plan.node.process.MergeSortNode;
+import org.apache.iotdb.db.mpp.plan.planner.plan.node.process.SingleDeviceViewNode;
+import org.apache.iotdb.db.mpp.plan.planner.plan.node.process.TimeJoinNode;
+import org.apache.iotdb.db.mpp.plan.planner.plan.node.process.TransformNode;
 
 import org.junit.Test;
 
 import java.util.List;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
 public class AlignedByDeviceTest {
 
   @Test
   public void test1Device1Region() {}
 
+  @Test
+  public void testDiffFunction2Device3Region() {
+    QueryId queryId = new QueryId("test_special_process_align_by_device_2_device_3_region");
+    MPPQueryContext context =
+        new MPPQueryContext("", queryId, null, new TEndPoint(), new TEndPoint());
+    // ------------------------------------------------------------------------------------------------
+    // Note: d1.s1[1] means a SeriesScanNode with target series d1.s1 and its data region is 1
+    //
+    //                                       DeviceViewNode
+    //                                  ___________|__________
+    //                                 /                      \
+    //                           TransformNode                 Exchange
+    //                                |                             |
+    //                           TimeJoinNode                  TransformNode
+    //                           /     |      \                     |
+    //                     d1.s1[1]  d1.s2[1]  Exchange         TimeJoinNode
+    //                                            |               /      \
+    //                                        TimeJoinNode  d22.s1[3]   d22.s2[3]
+    //                                        /      \
+    //                                  d1.s1[2]    d1.s2[2]
+    // ------------------------------------------------------------------------------------------------
+    String sql = "select diff(s1), diff(s2) from root.sg.d1,root.sg.d22 align by device";
+    Analysis analysis = Util.analyze(sql, context);
+    PlanNode logicalPlanNode = Util.genLogicalPlan(analysis, context);
+    DistributionPlanner planner =
+        new DistributionPlanner(analysis, new LogicalQueryPlan(context, logicalPlanNode));
+    DistributedQueryPlan plan = planner.planFragments();
+    assertEquals(3, plan.getInstances().size());
+    PlanNode f1Root =
+        plan.getInstances().get(0).getFragment().getPlanNodeTree().getChildren().get(0);
+    PlanNode f2Root =
+        plan.getInstances().get(1).getFragment().getPlanNodeTree().getChildren().get(0);
+    PlanNode f3Root =
+        plan.getInstances().get(2).getFragment().getPlanNodeTree().getChildren().get(0);
+    assertTrue(f1Root instanceof DeviceViewNode);
+    assertTrue(f2Root instanceof TimeJoinNode);
+    assertTrue(f3Root instanceof TransformNode);
+    assertTrue(f1Root.getChildren().get(0) instanceof TransformNode);
+    assertTrue(
+        f1Root.getChildren().get(0).getChildren().get(0).getChildren().get(2)
+            instanceof ExchangeNode);
+    assertTrue(f3Root.getChildren().get(0) instanceof TimeJoinNode);
+  }
+
+  @Test
+  public void testDiffFunctionWithOrderByTime2Device3Region() {
+    QueryId queryId =
+        new QueryId("test_special_process_align_by_device_with_order_by_time_2_device_3_region");
+    MPPQueryContext context =
+        new MPPQueryContext("", queryId, null, new TEndPoint(), new TEndPoint());
+    // ------------------------------------------------------------------------------------------------
+    // Note: d1.s1[1] means a SeriesScanNode with target series d1.s1 and its data region is 1
+    //
+    //                                       MergeSortNode
+    //                                  ___________|______________
+    //                                 /                           \
+    //                         SingleDeviceViewNode             Exchange
+    //                                |                             |
+    //                           TransformNode              SingleDeviceViewNode
+    //                                |                             |
+    //                           TimeJoinNode                  TransformNode
+    //                           /     |      \                     |
+    //                     d1.s1[1]  d1.s2[1]  Exchange         TimeJoinNode
+    //                                            |               /      \
+    //                                       TimeJoinNode  d22.s1[3]   d22.s2[3]
+    //                                        /      \
+    //                                  d1.s1[2]    d1.s2[2]
+    // ------------------------------------------------------------------------------------------------
+    String sql =
+        "select diff(s1), diff(s2) from root.sg.d1,root.sg.d22 order by time align by device";
+    Analysis analysis = Util.analyze(sql, context);
+    PlanNode logicalPlanNode = Util.genLogicalPlan(analysis, context);
+    DistributionPlanner planner =
+        new DistributionPlanner(analysis, new LogicalQueryPlan(context, logicalPlanNode));
+    DistributedQueryPlan plan = planner.planFragments();
+    assertEquals(3, plan.getInstances().size());
+    PlanNode f1Root =
+        plan.getInstances().get(0).getFragment().getPlanNodeTree().getChildren().get(0);
+    PlanNode f2Root =
+        plan.getInstances().get(1).getFragment().getPlanNodeTree().getChildren().get(0);
+    PlanNode f3Root =
+        plan.getInstances().get(2).getFragment().getPlanNodeTree().getChildren().get(0);
+    assertTrue(f1Root instanceof MergeSortNode);
+    assertTrue(f2Root instanceof TimeJoinNode);
+    assertTrue(f3Root instanceof SingleDeviceViewNode);
+    assertTrue(f1Root.getChildren().get(0) instanceof SingleDeviceViewNode);
+    assertTrue(
+        f1Root.getChildren().get(0).getChildren().get(0).getChildren().get(0).getChildren().get(2)
+            instanceof ExchangeNode);
+    assertTrue(f3Root.getChildren().get(0).getChildren().get(0) instanceof TimeJoinNode);
+  }
+
   private LogicalQueryPlan constructLogicalPlan(List<String> series) {
     return null;
   }