我在Firebird上运行SP并且无法找到将代码转换为MS SQL Server SP的方法
这是代码:
我有一张表来获取数据。 一个字段称为" iznos"用于数据汇总和一个字段用于识别按类别汇总的差异
create or alter procedure SOME_PROCEDURE (
B_Date date,
E_Date date)
returns(
Dat date,
Value1 decimal(18,2),
Value2 decimal(18,2),
Value3 (18,2))
AS
BEGIN
FOR
SELECT gk.date
FROM gk
WHERE
gk.date BETWEEN :B_Date AND :E_Date
GROUP BY 1
INTO :Dat
DO
BEGIN
/* Value 1 */
SELECT sum(iznos) from gk where gk.category=1 and gk.datum=:Dat
INTO :Value1;
/* Value 2 */
SELECT sum(iznos) from gk where gk.category=2 and gk.datum=:Dat
INTO :Value2;
/* Value 3 */
SELECT sum(iznos) from gk where gk.category=3 and gk.datum=:Dat
INTO :Value3;
suspend;
end
end
答案 0 :(得分:0)
您可以使用PIVOT
解决此问题:
select datum, [1] as Value1, [2] as Value2, [3] as Value3
from (
select datum, category, iznos
from gk
where datum between @B_Date AND @E_Date
) as src
pivot (
sum(src.iznos)
for src.category in ([1], [2], [3])
) as pvt
这与Firebird存储过程没有完全相同的效果,因为它为gk
中的每一行返回一行。如果您希望获得完全相同的结果,则可能需要将gk
加入上述查询。
如果您打算在select中使用此存储过程(可以在Firebird中使用,但不能在SQL Server中使用),则需要将其转换为table-valued user-defined function。
您也可以创建视图。在这种情况下,需要删除where
子句。
TSQL中的小例子:
create table #example (
datum date,
category int,
val int
);
insert into #example(datum, category, val) values
('2015-07-24', 1, 1),
('2015-07-24', 2, 1),
('2015-07-24', 3, 1),
('2015-07-24', 1, 1),
('2015-07-24', 2, 1),
('2015-07-25', 3, 1);
select datum, [1] as Value1, [2] as Value2, [3] as Value3
from (
select datum, category, val
from #example
) as src
pivot (
sum(src.val)
for src.category in ([1], [2], [3])
) as pvt;
drop table #example;