4

我有查询,我在哪里调用函数StoreFlowsByDates

select
  sum(a.beglocalamount+a.localamount)
from
 StoreFlowsByDates(ib_encodedate(EXTRACT(YEAR FROM CURRENT_DATE),1 ,1), ib_encodedate(EXTRACT(YEAR FROM CURRENT_DATE), 12 ,31), '', '', '', '', '', '', '', 'N', 'N', 'N', 'N', '1000000101', '') a

此函数返回选定期间的值。我需要编辑此查询以返回一年中每个月的值。就像是:

select
  sum(a.beglocalamount+a.localamount),
  [SELECTED_MONTH]
from
 StoreFlowsByDates(ib_encodedate(EXTRACT(YEAR FROM CURRENT_DATE),[SELECTED_MONTH] ,1), ib_encodedate(EXTRACT(YEAR FROM CURRENT_DATE), [SELECTED_MONTH] ,31), '', '', '', '', '', '', '', 'N', 'N', 'N', 'N', '1000000101', '') a
group by
[SELECTED_MONTH]

但在从 1 到 12 的循环中。这样的事情甚至可能吗?

4

1 回答 1

5

您不需要循环,而是可以加入的一系列简单整数。

整数表

在 SQL 中,通常为此使用整数表。例如,

CREATE TABLE UTIL$KILO (i INTEGER NOT NULL); -- one thousand integers, 0 – 999
INSERT INTO UTIL$KILO (i) VALUES (0);
INSERT INTO UTIL$KILO (i) VALUES (1);
...
INSERT INTO UTIL$KILO (i) VALUES (999);

您的系列是如此之小,以至于您可以合理地将这样的结果集内联:

    SELECT SUM(...),
           i AS "MONTH"
      FROM (SELECT 1 AS i        --
              UNION ALL          -- We'll just enumerate the months here
            SELECT 2             --
              UNION ALL          --
            ...                  --
            SELECT 12) month_nos
CROSS JOIN StoreFlowsByDates(ib_encodedate(..., i, ...)...)
  GROUP BY 2;

系列生成过程

一些 RDBMS 提供函数来生成这样的序列,并且可以编写一个 Firebird可选择的存储过程来达到同样的效果:

-- UTIL$RANGE(start, stop, step)
--
-- Firebird selectable stored procedure for producing integer ranges.
-- (Public Domain)
--
CREATE EXCEPTION util$err_range_zero_step 'step size may not be zero';
SET TERM !!;
CREATE PROCEDURE util$range("Start" INTEGER, "Stop" INTEGER, "Step" INTEGER)
  RETURNS (i INTEGER) AS
BEGIN
  IF ("Step" > 0) THEN BEGIN
    i = "Start";
    WHILE (i <= "Stop") DO BEGIN
      SUSPEND;
      i = i + "Step";
    END
  END
  ELSE IF ("Step" < 0) THEN BEGIN
    i = "Start";
    WHILE (i >= "Stop") DO
    BEGIN
      SUSPEND;
      i = i + "Step";
    END
  END
  ELSE IF ("Step" = 0) THEN
    EXCEPTION util$err_range_zero_step;
  -- ELSE return empty set
END !!
SET TERM ;!!

然后查询如下所示:

    SELECT SUM(...),
           i AS "MONTH"
      FROM util$range(1, 12, 1)
CROSS JOIN StoreFlowsByDates(ib_encodedate(..., i, ...)...)
  GROUP BY 2;
于 2013-11-07T15:50:21.167 回答