2015-09-18 52 views
1

我有一个复杂的请求。我必须在PHP中做如下图所示的报告。 Part summarized yield必须跨计算填写。 就像我在公式栏中解释的那样,part summarized yield中的值取自location yieldpart summarized yield之间的计算。 (见本公式)SQL Server中的交叉计算

Example excel report

如何做到这一点的计算在PHP报告? 我已经尝试使用游标,但它仍然无法正常工作。

这是我的光标计算:

--In PHP file, i make query to insert data first to table tyield_summary 
--Cursor to input yield_summary 
Declare @nourut varchar(2), @maxnourut varchar(2), @bpnum varchar(20), @pnum varchar(20), @curnourut varchar(2), @psum decimal(18,2), @ysum decimal(18,2) 

DECLARE StockCursor CURSOR 
FOR 

select no_urut, part_number, Part_Summary 
from tyield_summary 
where no_urut<>'99' 
order by part_number desc, no_urut asc 

set @bpnum='' 

OPEN StockCursor 
FETCH NEXT FROM StockCursor INTO @nourut, @pnum, @psum 

WHILE @@FETCH_STATUS=0 
BEGIN 


    if @[email protected] 
    begin 

    select top 1 @curnourut=no_urut 
    from tyield_summary 
    where [email protected] 
    and no_urut<@nourut 
    order by no_urut desc 

    set @[email protected] 

    select @maxnourut = max(no_urut) from tyield_summary 
    where [email protected] 


    update tyield_summary 
    set yield_summary = case when Part_Summary=0 then @psum else (Part_Summary*@psum)/100 end 
    where [email protected] 
    and [email protected] 



    end 
    else 
    begin 

    set @[email protected] 

    end 

    FETCH NEXT FROM StockCursor INTO @nourut, @pnum, @psum 

END 

CLOSE StockCursor 
DEALLOCATE StockCursor 

这里表结构: enter image description here

我需要填写使用公式-i显示在Excel part_summary字段。 在公式显示中,使用交叉字段进行计算。

+0

看到结果你坚持在哪里?请提供表格结构。 –

+0

我已经更新我的文章并提供表格结构。请帮忙 –

+0

将图像作为“表格结构”发布是懒惰的人。无论如何,只需使用您的排序/聚合条件创建一个行号列,然后计算每行* row +1,或者如果没有聚合中实际行的下一个值,只需获取行值。也避免游标 – jean

回答

0

这里是你如何做到这一点(没有讨厌的游标)。 只需在您的订购/聚合条件中使用行号即可查找下一行, 左边每行加入其下一行(不要忘记聚合条件)并完成。

让我们用一个例子(这里是你properlu如何发布表结构):

create table Lazydude 
(
    Partno varchar(20) not null 
    ,Seq int not null 
    ,[Value] float not null 
) 
GO 

insert into Lazydude (Partno, Seq, [Value]) 
values 
('AAA', 1, 77.7) 
,('BBB', 0, 2) 
,('BBB', 3, 3) 
,('BBB', 9, 5) 
,('CCC', 1, 33.3) 
,('CCC', 2, 33.3) 
GO 

,并使用行号来选择,并在使用结果自联接

with Temp as(
    select Partno, Seq, [Value] 
    ,ROW_NUMBER() OVER(ORDER BY Partno, Seq) AS [Row] 
    from Lazydude 
) 
select t0.Partno, t0.Seq, t0.[Value], t0.[Row] 
, t1.row as [Next Row], t1.[Value] as [Next Value] 
, case when t1.row is null 
    then t0.[Value] 
    else t0.Value * t1.Value 
    end as [The Calculation] 
from Temp t0 
left join Temp t1 on t1.[Row] = t0.[Row] + 1 and t1.Partno = t0.Partno 

你可以在SQL Fiddle

Partno Seq Value Row Next Row Next Value The Calculation 
AAA  1 77.7 1 (null)  (null)  77.7 
BBB  0 2  2 3   3   6 
BBB  3 3  3 4   5   15 
BBB  9 5  4 (null)  (null)  5 
CCC  1 33.3 5 6   33.3   1108.8899999999999 
CCC  2 33.3 6 (null)  (null)  33.3 
+0

非常感谢您珍妮。我尝试在我的SQL命令并运行完美。即使在最后一个seq仍然有错误。我会尽力解决它。非常感谢您的帮助 –