Solved

SQL - Running Value

Posted on 2014-11-08
7
111 Views
Last Modified: 2014-11-09
I created a sql query to calculate a running value to calculate shortage.  However, I can't seem to get it to work correctly.

This is what I'm expecting.  The RunningValue column is what I'm after.
Expected Result
However, I'm getting the following instead with my current SQL Query.
 Current Output
Here's my sql script.  Maybe I'm not doing something right.
SELECT	J.START_DATE, J.JOB_ID, J.ITEM_ID, J.REQ_QTY, J.ON_HAND,

		(
		SELECT	MAX(J2.ON_HAND) - SUM(J2.REQ_QTY)
		FROM	JOB_ORDER J2
		WHERE	J2.ITEM_ID = J.ITEM_ID
				AND J2.START_DATE <= J.START_DATE
				AND J2.JOB_ID <= J.JOB_ID
		)
		
FROM	JOB_ORDER J
WHERE	J.ITEM_ID = 'GDM001'
		AND J.START_DATE BETWEEN '2014-11-7' AND '2014-11-14'

Open in new window

0
Comment
Question by:holemania
  • 3
  • 3
7 Comments
 
LVL 14

Expert Comment

by:ThomasMcA2
Comment Utility
I have some observations, but not an outright solution.

Using Max() probably does not do what you want. That's because the quantity on hand (QOH) will fluctuate as orders are processed.

On a related note, the source data looks odd. It would be odd for orders to be unprocessed for a week, and for the QOH to remain the same for an entire week.

Also, your data is not sorted by the Job ID. That will make the Running Values misleading, even when they are being evaluated correctly.
0
 
LVL 48

Expert Comment

by:PortletPaul
Comment Utility
|   START_DATE | JOB_ID | ITEM_ID | REQ_QTY | ON_HAND | PREV_QTY | COLUMN_6 |
|--------------|--------|---------|---------|---------|----------|----------|
| Nov, 07 2014 |  42006 |  GDM001 |       4 |      15 |        4 |       11 |
| Nov, 11 2014 |  42448 |  GDM001 |  13.375 |      15 |   17.375 |   -2.375 |
| Nov, 13 2014 |  42350 |  GDM001 |       4 |      15 |   29.375 |  -14.375 |
| Nov, 13 2014 |  42007 |  GDM001 |       4 |      15 |   29.375 |  -14.375 |
| Nov, 13 2014 |  42424 |  GDM001 |       4 |      15 |   29.375 |  -14.375 |
| Nov, 14 2014 |  42656 |  GDM001 |     1.5 |      15 |   30.875 |  -15.875 |

Open in new window

Produced by:
SELECT
      J.START_DATE
    , J.JOB_ID
    , J.ITEM_ID
    , J.REQ_QTY
    , J.ON_HAND
    , CA.PREV_QTY
    , J.ON_HAND - CA.PREV_QTY
FROM JOB_ORDER J
      CROSS APPLY (
            SELECT
                  SUM(J2.REQ_QTY)
            FROM JOB_ORDER J2
            WHERE J2.ITEM_ID = J.ITEM_ID
            AND J2.START_DATE <= J.START_DATE
      ) CA (PREV_QTY)
WHERE J.ITEM_ID = 'GDM001'
AND ( J.START_DATE >= '20141107' AND J.START_DATE < '20141115' )
;

Open in new window

Please provide sample data with questions of this nature. While that image of the data may be helpful in describing the problem it isn't of so much use in solving the problem. e.g.
CREATE TABLE JOB_ORDER 
	([Start_Date] datetime, [Job_ID] int, [Item_ID] varchar(6), [Req_Qty] decimal(12,3), [On_Hand] decimal(12,3))
;
	
INSERT INTO JOB_ORDER
	([Start_Date], [Job_ID], [Item_ID], [Req_Qty], [On_Hand])
VALUES
	('2014-11-07 00:00:00', 42006, 'GDM001', 4, 15),
	('2014-11-11 00:00:00', 42448, 'GDM001', 13.375, 15),
	('2014-11-13 00:00:00', 42350, 'GDM001', 4, 15),
	('2014-11-13 00:00:00', 42007, 'GDM001', 4, 15),
	('2014-11-13 00:00:00', 42424, 'GDM001', 4, 15),
	('2014-11-14 00:00:00', 42656, 'GDM001', 1.5, 15)
;

Open in new window

And with that data it is possible to test a proposed solution.

see it working at: http://sqlfiddle.com/#!3/f77db5/1

Please note I have altered the method used for the date range filter.
See: "Beware of Between"

and the safest date literal in SQL Server is YYYYMMDD
0
 

Author Comment

by:holemania
Comment Utility
Thanks PortletPaul.

Anyway to get it so that the running value as followed:

|   START_DATE | JOB_ID | ITEM_ID | REQ_QTY | ON_HAND | PREV_QTY | COLUMN_6 |
|--------------|--------|---------|---------|---------|----------|----------|
| Nov, 07 2014 |  42006 |  GDM001 |       4 |      15 |        4 |       11 |
| Nov, 11 2014 |  42448 |  GDM001 |  13.375 |      15 |   17.375 |   -2.375 |
| Nov, 13 2014 |  42350 |  GDM001 |       4 |      15 |   29.375 |  -6.375 |
| Nov, 13 2014 |  42007 |  GDM001 |       4 |      15 |   29.375 |  -10.375 |
| Nov, 13 2014 |  42424 |  GDM001 |       4 |      15 |   29.375 |  -14.375 |
| Nov, 14 2014 |  42656 |  GDM001 |     1.5 |      15 |   30.875 |  -15.875 |

Open in new window


Seems to repeat -14.375 since the date is the same.  However, I also need it to sum correctly for each line.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:holemania
Comment Utility
Looks like the following works, but only with SQL 2012.  Unfortunately, that's only my test environment and all my production SSRS reports as well as databases are on SQL 2005 and 2008.

DECLARE @SPOUTPUT TABLE(
		START_DATE DATE,
		JOB_ID VARCHAR(30),
		ITEM_ID VARCHAR(30),
		REQ_QTY DECIMAL(15, 4),
		ON_HAND DECIMAL(15, 4)
		)
		
INSERT INTO @SPOUTPUT
VALUES('2014-11-7', '42006', 'GDM001', '4', '15')
INSERT INTO @SPOUTPUT
VALUES('2014-11-11', '42448', 'GDM001', '13.375', '15')
INSERT INTO @SPOUTPUT
VALUES('2014-11-13', '41320', 'GDM001', '4', '15')
INSERT INTO @SPOUTPUT
VALUES('2014-11-13', '42007', 'GDM001', '4', '15')
INSERT INTO @SPOUTPUT
VALUES('2014-11-13', '42425', 'GDM001', '4', '15')
INSERT INTO @SPOUTPUT
VALUES('2014-11-14', '42656', 'GDM001', '1.5', '15')		
		
SELECT	S.START_DATE, S.JOB_ID, S.ITEM_ID, S.REQ_QTY, S.ON_HAND,
		S.ON_HAND - SUM(S.REQ_QTY) OVER (PARTITION BY S.ITEM_ID ORDER BY S.START_DATE, S.JOB_ID)
FROM	@SPOUTPUT S
ORDER BY S.START_DATE, S.JOB_ID

Open in new window


The above produce the result I need.
START_DATE JOB_ID                         ITEM_ID                        REQ_QTY                                 ON_HAND                                 RUNNING_VALUE
---------- ------------------------------ ------------------------------ --------------------------------------- --------------------------------------- ---------------------------------------
2014-11-07 42006                          GDM001                         4.0000                                  15.0000                                 11.0000
2014-11-11 42448                          GDM001                         13.3750                                 15.0000                                 -2.3750
2014-11-13 41320                          GDM001                         4.0000                                  15.0000                                 -6.3750
2014-11-13 42007                          GDM001                         4.0000                                  15.0000                                 -10.3750
2014-11-13 42425                          GDM001                         4.0000                                  15.0000                                 -14.3750
2014-11-14 42656                          GDM001                         1.5000                                  15.0000                                 -15.8750

Open in new window

0
 
LVL 48

Expert Comment

by:PortletPaul
Comment Utility
"Sum correctly for each line"

Exactly how do you decide what is correct? That isn't stated.
0
 
LVL 48

Accepted Solution

by:
PortletPaul earned 500 total points
Comment Utility
Assuming JOB_ID is the tie breaker within a day:
| START_DATE | JOB_ID | ITEM_ID | REQ_QTY | ON_HAND | PREV_QTY | RUNNING_QTY |
|------------|--------|---------|---------|---------|----------|-------------|
| 2014-11-07 |  42006 |  GDM001 |       4 |      15 |        4 |          11 |
| 2014-11-11 |  42448 |  GDM001 |  13.375 |      15 |   17.375 |      -2.375 |
| 2014-11-13 |  42007 |  GDM001 |       4 |      15 |   21.375 |      -6.375 |
| 2014-11-13 |  42350 |  GDM001 |       4 |      15 |   25.375 |     -10.375 |
| 2014-11-13 |  42424 |  GDM001 |       4 |      15 |   29.375 |     -14.375 |
| 2014-11-14 |  42656 |  GDM001 |     1.5 |      15 |   30.875 |     -15.875 |

Open in new window


Produced by (and should run on SQL 2005):
WITH CTE
AS (
    SELECT
          START_DATE
        , JOB_ID
        , ITEM_ID
        , REQ_QTY
        , ON_HAND
        , ROW_NUMBER() OVER(PARTITION BY ITEM_ID
                            ORDER BY START_DATE, JOB_ID) AS RN
    FROM JOB_ORDER
   )
SELECT
      CONVERT(VARCHAR(10),J.START_DATE,121) START_DATE
    , J.JOB_ID
    , J.ITEM_ID
    , J.REQ_QTY
    , J.ON_HAND
    , ca.prev_qty
    , J.ON_HAND - ca.prev_qty AS RUNNING_QTY
FROM CTE J
CROSS APPLY (
            SELECT
                  ISNULL(SUM(J2.REQ_QTY),0)
            FROM CTE J2
            WHERE J2.ITEM_ID = J.ITEM_ID
            AND J2.START_DATE <= J.START_DATE
            AND J2.RN <= J.RN
             ) ca (prev_qty)
WHERE J.ITEM_ID = 'GDM001'
AND J.START_DATE >= '20141107' AND J.START_DATE < '20141115'
;

Open in new window

0
 

Author Closing Comment

by:holemania
Comment Utility
Awesome.  Thank you.
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

In this article I will describe the Copy Database Wizard method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
This video discusses moving either the default database or any database to a new volume.
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…

728 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now