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

问题描述 投票:0回答:2

我有两个查询语句,它们是相同的,只有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
;
oracle function plsql boilerplate
2个回答
2
投票

对于现实世界的项目,您可以使用from子句中的动态SQL和函数 - 从长远来看更好。

我讨厌两次编写相同或类似的代码。所以最好的选择就是这样

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

1
投票

这不使用一个函数,它必须使用动态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
      )
)
;

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

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
;

我不确定它能让你获得那么多......

© www.soinside.com 2019 - 2024. All rights reserved.