创建 Oracle 函数 - 如何减少样板代码

Create Oracle functions - how to reduce boilerplate code

我有两个查询语句,它们非常相同,只有 3 列不同,我用来创建数据透视表。前两列给出数据透视表的维度,而第三列包含我们调用聚合函数的数据。

我是 SQL 的新手,所以我想知道是否有任何干净的方法来定义一个函数,其中包含 3 个列名参数和一个提供聚合函数的第 4 个参数。

SELECT *
FROM (
  SELECT SDDCTO, SDSRP4, SDSOQS
  FROM MyTable
)
PIVOT (
  sum(SDSOQS)  
  for SDDCTO 
  IN ('EB' AS EB 
      'EL' AS EL, 
      'ER' AS ER, 
      'ES' AS ES, 
      'E1' AS E1, 
      'E2' AS E2, 
      'E5' AS E5 
      'E9' AS E9
      )
)
ORDER BY SDSRP4
;

-- Same query with different columns and aggregate function
SELECT *
FROM (
  SELECT SDDCTO, SDMCU, SDAEXP
  FROM MyTable
)
PIVOT (
  avg(SDAEXP)  
  for SDDCTO 
  IN ('EB' AS EB, 
      'EL' AS EL, 
      'ER' AS ER, 
      'ES' AS ES, 
      'E1' AS E1, 
      'E2' AS E2, 
      'E5' AS E5, 
      'E9' AS E9
      )
)
ORDER BY SDMCU
;

这不使用必须使用动态的函数 SQL 维护起来可能比两个单独的查询更痛苦;但您可以创建一个将两个聚合合二为一的视图:

CREATE VIEW MyView AS
SELECT *
FROM (
  SELECT SDDCTO, SDSRP4, SDSOQS, SDMCU, SDAEXP
  FROM MyTable
)
PIVOT (
  sum(SDSOQS) as SUM_SDOQS,
  avg(SDAEXP) as AVG_SDAEXP
  for SDDCTO 
  IN ('EB' AS EB, 
      'EL' AS EL, 
      'ER' AS ER, 
      'ES' AS ES, 
      'E1' AS E1, 
      'E2' AS E2, 
      'E5' AS E5, 
      'E9' AS E9
      )
)
;

... 然后在您的两个查询中查询视图,而不是 table:

SELECT SDSRP4, EB_SUM_SDOQS, EL_SUM_SDOQS, ER_SUM_SDOQS, ES_SUM_SDOQS,
  E1_SUM_SDOQS, E2_SUM_SDOQS, E5_SUM_SDOQS, E9_SUM_SDOQS
FROM MyView
ORDER BY SDSRP4
;

SELECT SDMCU, EB_AVG_SDAEXP, EL_AVG_SDAEXP, ER_AVG_SDAEXP, ES_AVG_SDAEXP,
  E1_AVG_SDAEXP, E2_AVG_SDAEXP, E5_AVG_SDAEXP, E9_AVG_SDAEXP
FROM MyView
ORDER BY SDMCU
;

虽然我不确定它是否让你受益匪浅...

对于较早的现实世界项目,您会熟悉动态 SQL 和 from 子句中的函数 - 在长 运行.

中更好

我讨厌将相同或相似的代码写两次。所以最好的选择是

select ...
from table(plsql_package ( parameters ))