替代 SQL 查询

Alternative SQL queries

此处显示的此查询用于查找替代方法,但还需要执行其他两种方法。

考虑以下 SQL 代码:

SELECT building, SUM(budget) AS totalbudget
FROM department 
GROUP BY building
HAVING SUM(budget) > 10000;

创建三种替代方法以获得完全相同的结果,从而消除 HAVING 子句。并针对每个备选方案解释查询对性能的影响?

第一种方式:

SELECT building, totalbudget
FROM 
    (SELECT building, SUM(budget) AS totalbudget
     FROM department 
     GROUP BY building)
WHERE totalbudget > 10000;

还有另外两种方式...

选项 1:

SELECT *
FROM   department
MATCH_RECOGNIZE(
  PARTITION BY building
  MEASURES
    SUM(budget) AS totalBudget
  PATTERN (^ all_rows+ $)
  DEFINE
    all_rows AS 1 = 1
)
WHERE totalBudget > 10000

选项 2:

SELECT building,
       SUM(budget) AS totalbudget
FROM   department d
WHERE  10000 < (
  SELECT SUM(budget)
  FROM   department t
  WHERE  d.building = t.building
)
GROUP BY building

选项 3:

SELECT building,
       SUM(budget) AS totalbudget
FROM   department
GROUP BY building
ORDER BY totalbudget DESC
FETCH FIRST ( SELECT COUNT(*)
              FROM   (
                SELECT SUM(budget) AS total
                FROM   department
                GROUP BY building
              )
              WHERE total > 10000            ) ROWS ONLY;

And for each alternative explain the impact of the query on performance?

它们的性能都比使用 HAVING 差。

db<>fiddle here