我有查询,我在其中调用函数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的周期。这样的事情甚至可能吗?
答案 0 :(得分:5)
你不需要一个循环,但是你可以加入一个简单的整数序列。
在SQL中,通常会使用table of integers。如,
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 selectable stored procedure以获得相同的效果:
-- 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;