Question : Find Not In Order Stock Transaction

Hi All,

I have stock table structure below:

TMSTOCK.

1. TrsId
2. TrsDate
3. ItemCode
3. StockIn
4. StockDate

Sample Data:

TrsId     TrsDate        ItemCode   StockIn   StockOut
B1         2009/01/01   CCL           100         0
S1         2009/01/01   CCL           0             60
S2         2009/01/01   CCL           0             30
B2         2009/02/01   CCL           100         0
S3         2009/02/01   CCL           0             60
S4         2009/02/01   CCL           0             60

Transaction S4 is not in order since StockIn = 100 + 100 = 200
                                                   StockOut = 60 + 30 + 60 = 150 plus 160 equal to 210 then the S4 transaction is appropriate.

How could I find this kind of transaction in TMSTOCK?

Thank you.
     

Answer : Find Not In Order Stock Transaction

I assume you that to say out of order you need to have this order. That's why I've added identity field into solution. The SQL below will find your S4 transaction.

create table TMSTOCK(id int IDENTITY, trsid varchar(10),
stockin int, stockout int)

insert TMSTOCK VALUES('B1',100,0)
insert TMSTOCK VALUES('S1',0,60)
insert TMSTOCK VALUES('S2',0,30)
insert TMSTOCK VALUES('b2',100,0)
insert TMSTOCK VALUES('s3',0,60)
insert TMSTOCK VALUES('s4',0,60)
insert TMSTOCK VALUES('s5',100,0)

select * from TMSTOCK a
where
(select SUM(stockin)-SUM(stockout) from TMSTOCK b where b.id<=a.id) < 0

Random Solutions  
 
programming4us programming4us