SQL Server Closing Stock values to opening stock of Next month

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP

SQL Server Closing Stock values to opening stock of Next month



I have a stock table contains three columns: Month, Year and Closing Stock like this:


Month Year CLosingstock
------------------------------
Jan 2017 10
Feb 2017 20
Mar 2017 30
Dec 2017 40
Jan 2018 50
Feb 2018 60



I want to create the new column of Opening stock and the jan 2017 values(10) should be a opening stock to Feb 2017.So How i place the values and other months opening stock to closing stock of next month.




1 Answer
1



Use the window function LAG(). I am assuming your Month is a integer and not string


LAG()


Month


select *, OpeningStock = LAG(ClosingStock) OVER (ORDER BY Year, Month)
from YourTable






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

  1. Mr Benjamin went above and beyond their requirements to assist me with my loan which i used expand my pharmacy business,They were friendly, professional, and absolute gems to work with.I will recommend  anyone looking for loan to contact. 247officedept@gmail.com.WhatsApp ... + 19893943740.

    ReplyDelete

Post a Comment

Popular posts from this blog

Executable numpy error

PySpark count values by condition

Trying to Print Gridster Items to PDF without overlapping contents