Sql Query

Posted on 2014-02-19
Last Modified: 2014-02-21
Hi experts
I have a table which have inventory transactions  ( in and out)

I need a query which shows list of last all IN transactions where the sum of quantities equal to stock balance.

Question by:bmkdubai
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
  • 2
  • +1

Author Comment

ID: 39873066
database is sqlserver.

data is like


there are many receipts and issues marked I for in and O for out.

I need to get what are I transaction qty total is matching with the closing balance of a item.
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 39873126
first, the query of all the items with the "in" sum qty :
select itecode, sum(qty) 
  from transactions
where [in/out] = 'I'
  group by itecode 

Open in new window

in "stock" table, I presume you have also itecode and a closing_balance field:
select s.itecode, s.closing_balance, t.sum_qty
  from stock_table s
  left join ( select itecode, sum(qty)  sum_in
  from transactions
where [in/out] = 'I'
  group by itecode ) t
   on t.itecode = s.itecode 

Open in new window

so, if now you want to have only those items where the closing_balance = sum(qty)

select s.itecode, s.closing_balance, t.sum_qty
  from stock_table s
  join ( select itecode, sum(qty)  sum_in
  from transactions
where [in/out] = 'I'
  group by itecode ) t
   on t.itecode = s.itecode 
and t.sum_qty = s.closing_balance

Open in new window

if anything is unclear, please clarify more about the problem and the expected results.
LVL 40

Expert Comment

by:Vadim Rapp
ID: 39873348
> I need to get what are I transaction qty total is matching with the closing balance of a item.

1. Where do you take closing balance from?

2. let's say, the closing balance is 3, and you have these "in" transactions:

#         Qty
1          1
2          1
3          2
4          2

Which ones do you expect to be shown in the result?
Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

LVL 15

Expert Comment

ID: 39874199
Definitely need more info. "Data is like docno, docdate, itecode, description, in/out, qty" tells us nothing. "there are many receipts and issues marked I for in and O for out" tells little more. What is/are the table schema? Is there more than one table involved? Where is the stock balance derived.

We like to call ourselves experts, not psychics. :-)

What version of SQL Server are you using?

Clearly define the problem. For example (using my psychic abilities),
"I have a Transaction table with DocNo, DocDate, ItemCode, Description, I_0_Indicator and Qty. This table ties to a Stock table on DocNo and has a StockBalance. I need to identify rows in the Stock table where the sum of rows in the Transaction table with an I_O value of 'IN' equals the StockBalance value. Ignore I-O values of 'OUT'."

We can start to work with that.
LVL 15

Expert Comment

ID: 39875156
I have been duly (and properly) admonished for my last post, and to all, I offer an apology. Although the facts are sketchy, it should be our job to 'guide' the customer into defining the problem so that we can assist with a solution.

I use EE both to garner information on problems that I encounter (and for that I am very grateful) but also to return to the community knowledge that I've gleaned over the years. There should be no excuse to posting an inflammatory comment.

Please accept my apology and know that I will continue to assist in any possible way.

Author Comment

ID: 39875996
Dear All
I am using sqlserver 2008 r2

The purpose of the query is to find stock aging. there will be many in and out transactions.
Based on the date I can find out the closing balance as on a day or month or year whatever.
But for the financial analysis we need stock aging. In Manual process we find stock aging as on a particulat day will be .  

1. find out the closing balance of all the items as on a particular day.
2. get the last IN transactoins for all the items  with date, document number etc., (be sure when we sum all the quantities of IN of a particular item should match with the closing balance of the item.)
3. then make the stock aging based on the date.


closing balance as on 30/4/2014 is 13 and in quantities are

1/1/2013      2
10/2/2013  10
20/3/2014   6
30/4/2014    4
30/5/2014  10
30/6/2014  1

the result will be

10/2/2013   3
20/3/2014   6
30/4/2014    4

Please support
LVL 40

Accepted Solution

Vadim Rapp earned 500 total points
ID: 39876937
I'm sure it's possible to do with clever long sql, in one query, but I think the following is more straightforward and thus more maintainable. It's for one item.

/* create and populate the table to try out */
create table transactions(d datetime,qty int)
insert into transactions(d,qty) select '1/1/2013'  ,  2
insert into transactions(d,qty) select '2/10/2013' , 10
insert into transactions(d,qty) select '3/20/2014' ,  6
insert into transactions(d,qty) select '4/30/2014' , 4
insert into transactions(d,qty) select '5/30/2014' , 10
insert into transactions(d,qty) select '6/30/2014',  1

/* the query to find last transactions on or before @the_date totaling @closing_balance */

declare @closing_balance int, @the_date datetime
select @closing_balance=13, @the_date='2014-4-30'

declare c cursor local fast_forward for
	select d,qty from transactions where d <= @the_date
	order by d desc

create table #tmp(d datetime,qty int)

declare @running_total int, @qty int, @d datetime
select @running_total=0
open c
fetch c into @d,@qty
while @@fetch_status=0 and  @running_total < @closing_balance begin
	insert into #tmp(d, qty) 
	select @d,
		case when @running_total + @qty <= @closing_balance then @qty else @closing_balance-@running_total end
	set @running_total = @running_total + @qty
	fetch c into @d,@qty
close c; deallocate c
select * from #tmp order by d
drop table #tmp

Open in new window

Making it in one query would be much easier if not your requirement to include only partial qty of the earliest included transaction, in order to achieve exact match.

Author Comment

ID: 39877042
idea is good. I need extend a lot. like find stock balance as on user selection, there are many inventory items, I need to make aging based on the user parameter like (90,60,120 etc.,)

Author Closing Comment

ID: 39877044
good work

Featured Post

Enterprise Mobility and BYOD For Dummies

Like “For Dummies” books, you can read this in whatever order you choose and learn about mobility and BYOD; and how to put a competitive mobile infrastructure in place. Developed for SMBs and large enterprises alike, you will find helpful use cases, planning, and implementation.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
When are cursors useful? 8 61
MAC Dreamweaver connect to external MS SQL Server 2 39
SQL Query 20 22
Group ordersum by orderdate 3 18
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.
Via a live example, show how to setup several different housekeeping processes for a SQL Server.

734 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question