2016-12-24 50 views
0

我的表结构的第二排值是这样SQL查询来获取一列的前行值要插入的另一列

username Period Numberproduced stockonhand totalavailableforsale actualsale Inventoryremaining 

pranab  1  100    2000   2100     2000  100 
pranab  2  200    100    300     500   0 
pranab  3  400    0    400     100  300 
pranab  4  500    300    800     400  400 

期-1的stockinhand总是恒定= 2000。

stockinhand期间-2是周期-1 &的等

= inventoryremaining u能请告诉该查询来执行这一点。

+1

问题是太不清楚我的口味 –

+0

stockinhand期-1的总是恒定= 2000。 第2期的stockinhand是=第1期的库存剩余等等 – pranab

+0

您使用哪种rdbms? –

回答

0

如果Period领域是独一无二的增量,那么这个解决方案应该工作:

SELECT 
    A.* 
    , [stockinhand] = IIF(A.[Period] = 1, 2000, B.[inventoryremaining]) 
FROM 
    [Table] AS A 
     CROSS APPLY 
    (SELECT TOP 1 * 
    FROM 
     [Table] AS B 
    WHERE 
     A.[Period] > B.[Period] 
    ORDER BY 
     B.[Period] DESC 
    ) AS B 

还要注意的是,如果你使用SQL Server 2012或更高版本,LAGLEAD子句将简化的解决方案。

+0

Username filed is uique – pranab

+0

开个玩笑? :-)你有相同的'用户名'四次.. –

+0

用户名是相同的所有期间 – pranab

0

如果period是连续的(无缺口)使用 -

select t.* 
     ,coalesce 
     (
      (select  Inventoryremaining 
      from  mytable as t2 
      where  t2.period = t.period - 1 
      ) 
      ,2000 
     ) as stockonhand 

from mytable t 

其他用途 -

select t.* 
     ,coalesce 
     (
      (select  Inventoryremaining 
      from  mytable as t2 
      where  t2.period < t.period 
      order by t2.period 
      desc  limit 1 
      ) 
      ,2000 
     ) as stockonhand 

from mytable t 
+0

not working ..请重新检查错误消息是 - 致命错误:未捕获PDOException:SQLSTATE [21000]:基数冲突:1242子查询返回多于1行在C:\ xampp \ htdocs \ lampson \ C:\ xampp \ htdocs \ lampson \ calculation中计算.php:73堆栈轨迹:#0 C:\ xampp \ htdocs \ lampson \ calculation.php(73):PDOStatement-> execute()#1 {main}在线73 – pranab

+0

php可以请你纠正查询使用pdo语句 – pranab

+0

根据错误预计只有一个单行,但由于您的请求所有行都返回 –