DISTINCT和LAG窗口功能

时间:2018-04-06 20:06:00

标签: mysql sql sql-server postgresql

有简单的表格:

CREATE TABLE tab AS 
SELECT 1 AS t,   'G' AS company, 40 AS quote
UNION SELECT 2 , 'G',    60 
UNION SELECT 3 , 'S',    60 
UNION SELECT 4,  'S',    20;

并查询:

SELECT DISTINCT company, quote ,LAG(quote) OVER(PARTITION BY company ORDER BY t)
FROM tab;

输出 - 结果在RDBMS之间保持一致。

+---------+-------+------+
| company | quote | lag  |
+---------+-------+------+
| G       |    40 | null |
| S       |    60 | null |
| G       |    60 | 40   |
| S       |    20 | 60   |
+---------+-------+------+

DBFiddle Demo - PostgreSQL

DBFiddle Demo - SQL Server

DBFiddle Demo - Oracle 11g

DBFiddle Demo - MariaDB

DBFiddle Demo - MySQL 8.0

但是当我尝试进行一些计算时,我会得到不同的结果:

SELECT DISTINCT company, quote - LAG(quote) OVER(PARTITION BY company ORDER BY t)
FROM tab;

PostgreSQL / SQL Server / Oracle(正如我所料):

+---------+--------+
| company | result |
+---------+--------+
| G       | null   |
| G       | 20     |
| S       | null   |
| S       | -40    |
+---------+--------+

MariaDB的/ MySQL的:

+----------+--------+
| company  | result |
+----------+--------+
| G        | null   |
| S        | null   |
+----------+--------+

据我所知Logical Query Processing

  
      
  1. FROM
  2.   
  3. ON
  4.   
  5. JOIN
  6.   
  7. WHERE
  8.   
  9. GROUP BY
  10.   
  11. WITH CUBE / ROLLUP
  12.   
  13. HAVING
  14.   
  15. 选择
  16.   
  17. DISTINCT
  18.         

    ...

DISTINCTSELECT之后,所以正确的方法应该像PostgreSQL / SQL Server / Oracle。(是的,我知道我可以使用子查询/删除DISTINCT但它不是问题的一点)。

这种行为是错误还是正常工作(文档)?

1 个答案:

答案 0 :(得分:2)

绝对是MySQL和MariaDB中的错误。我已将问题报告给两个数据库,并链接回此堆栈溢出问题: