Some body please help about the Inventory FIFO (FIRST IN FISRT OUT ) query is very slow

I have table ''tran_stock''  to store a transaction (IN-OUT) of the stock. 
The problem is when the  transaction rows are more than 50000 the query to get the balance
stock (Total 'IN' - Total'Out' by FIFO) is very slow . Somebody please suggest me to do this.
This is my query
;WITH OrderedIn as (
    select *,ROW_NUMBER() OVER (PARTITION BY Stock_ID ORDER BY TranDate) as rn
    from Tran_Stock
    where TxnType = 'IN'  
), RunningTotals as (
    select  Stock_ID ,Qty,Price,Qty as Total,Cast(0 as decimal(10,2)) as PrevTotal ,  trandate , rn  from OrderedIn where rn = 1
    union all
    select  rt.Stock_ID,oi.Qty,oi.Price,Cast(rt.Total + oi.Qty as decimal(10,2)),Cast(rt.Total as decimal(10,2)) , oi.TranDate ,oi.rn 
    from
        RunningTotals rt
            inner join
        OrderedIn oi
            on
                rt.Stock_ID = oi.Stock_ID and
                rt.rn = oi.rn - 1
, TotalOut as (
select Stock_ID ,SUM(Qty) as Qty from Tran_Stock where TxnType='OUT'   group by Stock_ID
) ,  GrandTotal as 
select
     rt.Stock_ID , rt.QTY AS original ,SUM(CASE WHEN PrevTotal > isNULL(out.Qty, 0) THEN rt.Qty ELSE rt.Total - isNULL(out.Qty, 0) END) AS QTY , Price , SUM(CASE WHEN PrevTotal > isNULL(out.Qty, 0) THEN rt.Qty ELSE rt.Total - isNULL(out.Qty,
0) END * Price) AS Ending , rt.TranDate
from
    RunningTotals rt
        LEFT join
    TotalOut out
        on
            rt.Stock_ID = out.Stock_ID
where rt.Total > isNull(out.Qty , 0)
group by rt.Stock_ID , Price , rt.TranDate  , rt.QTY
) SELECT * FROM  GrandTotal  order by TranDate  option (maxrecursion 0)
AND  this is my Table with some example data
USE [TestInventory]
GO
/****** Object:  Table [dbo].[Tran_Stock]    Script Date: 12/15/2014 3:55:56 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Tran_Stock](
[TranID] [int] IDENTITY(1,1) NOT NULL,
[Stock_ID] [int] NULL,
[TranDate] [date] NULL,
[TxnType] [nvarchar](3) NULL,
[Qty] [decimal](10, 2) NULL,
[Price] [decimal](10, 2) NULL
) ON [PRIMARY]
GO
SET IDENTITY_INSERT [dbo].[Tran_Stock] ON 
INSERT [dbo].[Tran_Stock] ([TranID], [Stock_ID], [TranDate], [TxnType], [Qty], [Price]) VALUES (1, 1, CAST(0x81350B00 AS Date), N'IN', CAST(200.00 AS Decimal(10, 2)), CAST(750.00 AS Decimal(10, 2)))
INSERT [dbo].[Tran_Stock] ([TranID], [Stock_ID], [TranDate], [TxnType], [Qty], [Price]) VALUES (2, 1, CAST(0x85350B00 AS Date), N'OUT', CAST(100.00 AS Decimal(10, 2)), NULL)
INSERT [dbo].[Tran_Stock] ([TranID], [Stock_ID], [TranDate], [TxnType], [Qty], [Price]) VALUES (3, 1, CAST(0x8A350B00 AS Date), N'IN', CAST(50.00 AS Decimal(10, 2)), CAST(700.00 AS Decimal(10, 2)))
INSERT [dbo].[Tran_Stock] ([TranID], [Stock_ID], [TranDate], [TxnType], [Qty], [Price]) VALUES (4, 1, CAST(0x90350B00 AS Date), N'IN', CAST(75.00 AS Decimal(10, 2)), CAST(800.00 AS Decimal(10, 2)))
INSERT [dbo].[Tran_Stock] ([TranID], [Stock_ID], [TranDate], [TxnType], [Qty], [Price]) VALUES (5, 1, CAST(0x99350B00 AS Date), N'OUT', CAST(175.00 AS Decimal(10, 2)), NULL)
INSERT [dbo].[Tran_Stock] ([TranID], [Stock_ID], [TranDate], [TxnType], [Qty], [Price]) VALUES (6, 2, CAST(0x82350B00 AS Date), N'IN', CAST(150.00 AS Decimal(10, 2)), CAST(350.00 AS Decimal(10, 2)))
INSERT [dbo].[Tran_Stock] ([TranID], [Stock_ID], [TranDate], [TxnType], [Qty], [Price]) VALUES (7, 2, CAST(0x88350B00 AS Date), N'OUT', CAST(40.00 AS Decimal(10, 2)), NULL)
INSERT [dbo].[Tran_Stock] ([TranID], [Stock_ID], [TranDate], [TxnType], [Qty], [Price]) VALUES (8, 2, CAST(0x8C350B00 AS Date), N'OUT', CAST(10.00 AS Decimal(10, 2)), NULL)
INSERT [dbo].[Tran_Stock] ([TranID], [Stock_ID], [TranDate], [TxnType], [Qty], [Price]) VALUES (9, 2, CAST(0x98350B00 AS Date), N'IN', CAST(90.00 AS Decimal(10, 2)), CAST(340.00 AS Decimal(10, 2)))
INSERT [dbo].[Tran_Stock] ([TranID], [Stock_ID], [TranDate], [TxnType], [Qty], [Price]) VALUES (12, 2, CAST(0x98350B00 AS Date), N'IN', CAST(10.00 AS Decimal(10, 2)), CAST(341.00 AS Decimal(10, 2)))
INSERT [dbo].[Tran_Stock] ([TranID], [Stock_ID], [TranDate], [TxnType], [Qty], [Price]) VALUES (13, 2, CAST(0x99350B00 AS Date), N'OUT', CAST(30.00 AS Decimal(10, 2)), NULL)
INSERT [dbo].[Tran_Stock] ([TranID], [Stock_ID], [TranDate], [TxnType], [Qty], [Price]) VALUES (14, 2, CAST(0x81350B00 AS Date), N'IN', CAST(120.00 AS Decimal(10, 2)), CAST(350.00 AS Decimal(10, 2)))
INSERT [dbo].[Tran_Stock] ([TranID], [Stock_ID], [TranDate], [TxnType], [Qty], [Price]) VALUES (15, 2, CAST(0x89350B00 AS Date), N'OUT', CAST(90.00 AS Decimal(10, 2)), NULL)
INSERT [dbo].[Tran_Stock] ([TranID], [Stock_ID], [TranDate], [TxnType], [Qty], [Price]) VALUES (17, 3, CAST(0x89350B00 AS Date), N'IN', CAST(90.00 AS Decimal(10, 2)), CAST(350.00 AS Decimal(10, 2)))
INSERT [dbo].[Tran_Stock] ([TranID], [Stock_ID], [TranDate], [TxnType], [Qty], [Price]) VALUES (18, 3, CAST(0x8A350B00 AS Date), N'OUT', CAST(60.00 AS Decimal(10, 2)), NULL)
INSERT [dbo].[Tran_Stock] ([TranID], [Stock_ID], [TranDate], [TxnType], [Qty], [Price]) VALUES (19, 3, CAST(0x5D390B00 AS Date), N'OUT', CAST(20.00 AS Decimal(10, 2)), NULL)
INSERT [dbo].[Tran_Stock] ([TranID], [Stock_ID], [TranDate], [TxnType], [Qty], [Price]) VALUES (20, 1, CAST(0x81350B00 AS Date), N'IN', CAST(200.00 AS Decimal(10, 2)), CAST(750.00 AS Decimal(10, 2)))
INSERT [dbo].[Tran_Stock] ([TranID], [Stock_ID], [TranDate], [TxnType], [Qty], [Price]) VALUES (21, 1, CAST(0x85350B00 AS Date), N'OUT', CAST(100.00 AS Decimal(10, 2)), NULL)

Hi,
You dont have any Index on the table, so the filters (where part in the queries) and the sorting (order by, group by) make your query slow. it take time to sort or filter data without Index. It is like reading a book with 3k pages and trying to find a specific
subject. You have to read the all books, but if you have "table of contents" which is the book index, then this can be done fast.
* check the Execution plan (the image here show part of your query's execution plan). the query scan the all table 3 times...
there is one sort that use 81% of the query resources... I will go sleep soon (it is
23:58 In Israel now), and I don't know if I will have time to read the query itself and improved it, so lets start with indexes :-) 
** as a first step after or before you create the right Indexes you should remove the recursive all together. there is no reason for lopping the data when you can use it as a SET. This is where the relational database's power come to life :-)
for example check this code. I only use your first part of the code using the first 2 CTE tables. compare result.
;WITH
OrderedIn as (
select *,ROW_NUMBER() OVER (PARTITION BY Stock_ID ORDER BY TranDate) as rn
from Tran_Stock
where TxnType = 'IN'
, RunningTotals as (
select Stock_ID ,Qty, Price, Qty as Total, Cast(0 as decimal(10,2)) as PrevTotal, trandate , rn
from OrderedIn where rn = 1
union all
select
rt.Stock_ID, oi.Qty, oi.Price, Cast(rt.Total + oi.Qty as decimal(10,2))
,Cast(rt.Total as decimal(10,2))
, oi.TranDate ,oi.rn
from RunningTotals rt
inner join OrderedIn oi on rt.Stock_ID = oi.Stock_ID and rt.rn = oi.rn - 1
select * from RunningTotals
-- This will do the same as the above query
select
Stock_ID, Qty, Price
, SUM(Qty) over (PARTITION BY Stock_ID order by TranDate ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as Total
,TranDate--,TranID, TxnType
from Tran_Stock
where TxnType = 'IN'
order by Stock_ID
  Ronen Ariely
 [Personal Site]    [Blog]    [Facebook]

Similar Messages

  • How can i create Inventory FIFO (FIRST IN FISRT OUT ) stock query ?

    I want to create  Inventory FIFO query from this
    I have a receive item table to store the receive item (IN) and i have requisition table  (OUT).
    I want to create a FIFO query  order by
    receiveID , the output i expect is
    How can i do this ?

    declare @Stock table (Item char(3) not null,[Date] datetime not null,TxnType varchar(3) not null,Qty int not null,Price decimal(10,2) null,ReqNo varchar(4) null)
    insert into @Stock(Item ,  [Date] ,        TxnType, Qty,  Price , ReqNo) values
    ('ABC','20120401','IN',    200, 750.00 ,null),
    ('ABC','20120405','OUT',   100 ,null , 'R001'  ),
    ('ABC','20120410','IN',     50, 700.00 ,null),
    ('ABC','20120416','IN',     75, 800.00 ,null),
    ('ABC','20120425','OUT',   175, null  , 'R002' ),
    ('XYZ','20120402','IN',    150, 350.00 ,null),
    ('XYZ','20120408','OUT',   120 ,null  , 'R003' ),
    ('XYZ','20120412','OUT',    10 ,null  , 'R004' ),
    ('XYZ','20120424','IN',     90, 340.00 ,null);
    ;WITH  RunningTotals as (
    select A.Item , A.Qty , A.Price ,  A.Total , total - A.qty AS PrevTotal,  rn FROM (
    select 
    Item , qty , Price
    , SUM(Qty) over (PARTITION BY Item order by [Date] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as total 
    ,ROW_NUMBER() OVER (PARTITION BY Item ORDER BY  [Date] ) as rn
    ,[Date]  
    from @Stock where TxnType = 'IN' )  A 
     )-- Select * from  RunningTotals    -- >> Sort FIFO by date
    , TotalOut as (
        select ReqNo , Item,SUM(Qty) as Qty  from @Stock where TxnType='OUT' group by Item , ReqNo
    ) Select * from TotalOut -- >> Item that out FIFO
    I want to get the price of any item in any ReqNo from RunningTotals by FIFO

  • HT5570 I have forgoten the security questions,i have tryed ewerithing to reset all of the instructions i have recived from the apple support team. I still can not reset the questions. Can some body please help me to reset them. Thank you and best regards

    I have forgoten the security questions,i have tryed ewerithing to reset all of the instructions i have recived from the apple support team. I still can not reset the questions. Can some body please help me to reset them. Thank you and best regards

    Since this is a user-to-user support forum, there isn't much we can do other than refer you to the following instructions and as noted in the instructions, then to Apple Support if you can't reset as shown in the instructions: If you forgot the answers to your Apple ID security questions

  • Some body please help!

    My phone was working perfectly fine I had just sent a txt message to my wife and recieved one back when i went to check the message the slide to open screen was waaaay zoomed in. i tried turing it off then back on then the reset by holding the home button and top button down for 10 seconds. and it is still zoomed in. can some one please help me i would really appreciate it. thank you.
    zak

    Page 190 of the manual:
    "Zoom in or out: Double-tap the screen with three fingers. By default, the screen is
    magnified by 200 percent. If you manually change the magnification (by using the tap-
    and-drag gesture, described below), iPhone automatically returns to that magnification
    when you zoom in by double-tapping with three fingers. "
    "Turn Zoom on or off: In Settings, choose General > Accessibility > Zoom and tap the
    Zoom On/Off switch. "

  • Please help about the limit request

    how to connect the internet for the mobile set 3110 classic
    because iam tried bye the contact provide service vodafone
    also contained the internet service provided with it service
    but massage comminig me tell me not contact or connection with internet
    please help me

    note:
    i am reading the note book about set and working it but wihtout ability
    what i do to connection with internet service

  • PLease Help- About the Apps

    (I pod touch owner)
    I want to downlowed a app on my i-touch
    but i am always seing apps for iphones, where do you fined apps for the thouch
    I want the free apps (for now)
    I am still a new member of apple nation, I dont really know my way through all this, I have been new for about 4 weks now
    so please explain and help'
    please, I need someone with experince and they know what they are talking about
    please and ty
    reply back

    Most of the applications work on your iTouch. Most applications will list which device they work on under the description. You won't be able to use applications that use the iPhones camera.

  • I am having problems installing yahoo firefox 3.6.8 I have the download i can not seem to get it to run can some one please help in the install after the download?

    I have firefox 3.0.15 and I am trying to move to 3.6.8. I have the download for 3.6.8 but when i try and run the install nothing seems to happen. I close firefox and reopen and check the rev and it is still 3.0.15. I must be doing something wrong with the install any suggestions?

    Hopefully this support article is what you need:
    http://support.mozilla.com/en-US/kb/Installing+Firefox

  • I dont have FaceTime on my 4G some body please help ! Thanks

    I've bought my 4G brandnew factory unlocked but still I cant run FaceTime app neither could i find it in settings.. does anyone have any idea of whats going on ?

    There is no FaceTime app: Settings>Phone>FaceTime>On.

  • Security question keep saying they are wrong and I know they are right. I can't change them cuz when I try it tells me to answer the questions. I have tried everything changing my account and all and still can't get it can some one please help me out.

    Security question keep saying they are wrong and I know they are right. I can't change them cuz when I try it tells me to answer the questions. I have tried everything changing my account and all and still can't get it can some one please help me out.

    Go here and select "Reset your password."  You will receive an email message with a link that bypasses the questions.  You will then be able to select and answer the questions again.

  • I am using iphone5 and when sending sms within 160 characters i am getting 2 sms counts deduction & i hear the message send sound twice. what is wrong here. can some one please help me here???

    i am using iphone5 and when sending sms within 160 characters i am getting 2 sms counts deduction & i hear the message send sound twice. what is wrong here. can some one please help me here???
    APPLE need to do something here!!!!!!1

    Hi...
    Thanks for your repaly .
    and i am not bale to post a question in developer forum i tried hard but i didnt get .Can you plz explain me how to post a question in developer forum this is very helpfull for me.Because i never did this thing.

  • HT6114 hello .. i am using mavericks OS  and it is showing it needs updates about 800 meg. and every time i download that it dosent do anything and again it is beginig to download again and again that.. please help me. the update is 10.9.2

    hello .. i am using mavericks OS  and it is showing it needs updates about 800 meg. and every time i download that it dosent do anything and again it is beginig to download again and again that.. please help me. the update is 10.9.2

    To answer the post title FireFox save all downloads automatically in the download folder, which you can find in the Documents folder. If you want to choose where to save your downloads go to tools>options>check always ask me where to save files.
    Secondly, I am assuming you have IE 8 installed as this is the only version that supports this fix that is currently not in beta. Go to control panel>internet options>advanced tab and reset the settings at the bottom. This may or may not fix the problem but it is a good first step.

  • My iPhones iTunes Radio doesn't work it says "iTunes radio is temporarily unavailable try again later" some one please help I really want to listen to the radio. 

    My iPhones iTunes Radio doesn't work it says "iTunes radio is temporarily unavailable try again later" some one please help I really want to listen to the radio.  please help my life depends on anyone who fixes the problem. 

    Your life depends on it? See this discussion: https://discussions.apple.com/thread/5345664

  • Can any body please help me

    Hi all,
    I have got a microstar MS 6340 ver 1 motherboard and i tried installing a PCI 32m nvida graphics card under windows xp. when ever i turn the PC on, i get no screen and the machine keeps beeping. the motherboard has an onboard graphice card but i dont know how to diable it. i have searched the web and cant find the manual to help me or someone to tell me what to do. can some one please help me disable the onboard graphic's.
    Thanks a million.
    Ps. if any body knows where to get the manual from, can you please post the link for me.
    Cheers )  )  )

    wird... in the v1 manual there is no indication for integrated VGA.... no wonder your board is the ms6340M v1 (is it??)....
    and thats a little difference
    http://www.msi.com.tw/program/products/mainboard/mbd/pro_mbd_detail.php?UID=131&MODEL=MS-6340M
    here is the manual for this mainboard
    http://download.msi.com.tw/support/mnu_exe/E6340Mv1.0.exe
    there is the frame buffer seting but there is no disable option for the on board vga....
    try the new bios... (but check if this is the corect board!!!)
    this is the link for v4.7 bios
    http://download.msi.com.tw/support/bos_exe/6340v47.exe
    [size=15]but be cereful i'm not responsible for any miss flushes  [/SIZE]  

  • I have CS6 Master Collection and Photoshop will not do a save as with any files that I am trying to save, can some one please help me?

    Can some one please help me with this?

    You would probably get some response if you posted your question in the Photoshop forum ...
    I'll move it there for you.
              - Dov

Maybe you are looking for

  • Power Mac Mirror Door DVI or ADC to SINGLE RCA VIDEO OUT to a TV...adapter?

    I have a Mirror Door G4 tower that I would like to use as a media center, with an old(er) Magnavox 19" television that only has the single yellow VIDEO IN jack, and the red and white audio L and R. Is there a converter cable that is similar to the on

  • Mobile workstation needs

    Hello all, Im new to the Adobe forum and have some questions regarding  mobile workstation needs.  I have grown very accustomed to using laptops and in the next month going to acquire a new machine. First off all, I dont want to offend those that use

  • A question regarding Virus protection..

    Hey! So my mac is about 2 years old now. I was wondering is there any virus protection programs that I should download to keep my Mac safe? Also, are there any viruses that CAN attack a Mac? As far as I have been using the mac there have been absolut

  • How to export Safari bookmarks to Chrome?

    I love the iPad Mini, but Chrome has some knockout features - like single-line URLs, and queries you can dictate. How can I export my Safari bookmarks into my Chrome Browser on the Mini?

  • Plz Update the website for Adobe Reader LE for Nokia N73 ME mobile

    Hello, Recently i bought Nokia N73 Music Edition which has Adobe Reader LE. For some reason the application does not launch any more. I searched in the nokia/adobe/google web but it seems that adobe's website is not updated and is not having Adobe Re