Php sql查询以获取一列的前一行值作为另一列的第二行值插入
我的桌子结构是这样的Php sql查询以获取一列的前一行值作为另一列的第二行值插入,php,sql,Php,Sql,我的桌子结构是这样的 username Period Numberproduced stockonhand totalavailableforsale actualsale Inventoryremaining pranab 1 100 2000 2100 2000 100 pranab 2 200 100
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 第2期库存量=第1期剩余库存量,依此类推 您能告诉查询执行此操作吗。如果期间字段是唯一且递增的,则此解决方案应能工作:
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或更新版本,则LAG或LEAD子句将简化解决方案。如果周期是连续的,则不使用间隔-
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
这个问题对我的口味来说太不清楚了,周期1的倒数总是常数=2000。第2阶段的stockinhand is=第1阶段的库存剩余量,依此类推,您使用哪种rdbms?Mysql和xamp serverUsername字段为uiqueUsername,所有周期的用户名都相同用户必须输入周期,生产数量和实际销售额由管理员声明。基于此计算,它不是唯一的。唯一意味着它没有重复项。这里有4个重复项。不工作..请重新检查错误消息是-致命错误:未捕获PDOException:SQLSTATE[21000]:基数冲突:1242子查询在C:\xampp\htdocs\lampson\calculation.php:73堆栈跟踪:0 C:\xampp\htdocs\lampson\calculation.php73:PDOStatement->execute 1{main}在第73行的C:\xampp\htdocs\lampson\calculation.php中抛出根据错误,只需要一行,但由于您的请求,所有行都将返回