Click here to Skip to main content
15,895,256 members
Please Sign up or sign in to vote.
1.80/5 (2 votes)
See more:
Hi All....

I have a Requirement to Add the Value of a Column in 'n' Consecutive Rows in Sql Server.... Am Unable to do that in a Query......

The Requirement is like this.... Let's Say Table_Y I have......
    Item     OrderNo      Qty
    -----    --------    -----
1     X       OrderZx     10
2     X       OrderCV     20
3     X       OrderAX     100
.     .          .         .
.     .          .         .
n     X       OrderX      300 --Calculate The Sum Untill Here (10+20+100+...+300)
n+1   Y       OrderA      15
n+2   Y       OrderB      23
n+3   X       OrderC      10 

The Task Here is I Have to Calculate the Sum of Qty For the X Item Untill OrderX(i.e. From OrderZx (1) to OrderX (n) All The Continous Orders For Item X).. I did it using While loop... But trying to do in d form of a query not in a loop or Cursor.... I Will get this Table Data on the fly... So Don't Know how Many Consecutive rows Will Have Same Item... i am thinking it can be acheived using Row_Number() But not Sure....
Please Note: The Output Required is: 10+20+100+...+300 (i.e.OrderZx(Qty)+OrderCV(Qty)+OrderAX(Qty)+...=OrderX(Qty) OrderX Should not be Included in Output...
Any Help Will be Appreciated...

Thanks
Raj
Posted
Updated 10-Jun-13 20:40pm
v5
Comments
Mike Meinz 10-Jun-13 9:30am    
Your requirement is not clear. Item X is in OrderC. Why wouldn't OrderC's Qty of 10 be included in the SUM?
Raja Sekhar S 11-Jun-13 3:12am    
Please Check the Comment i posted For your Answer Mike...
Zoltán Zörgő 10-Jun-13 9:37am    
This is a question of reporting (subtotal), not of a single query. You should not try to merge a reporting task into a single statement. If you really need this in t-sql write a stored procedure or function and use cursors.
Raja Sekhar S 11-Jun-13 3:20am    
Thanks for your Comment Zoltán Zörgő
I Want to use this in a Stored Procedure.... i Accomplished it using While Loop... But For the sake of Perfomance..... trying to write in d form of a query...
Zoltán Zörgő 11-Jun-13 3:47am    
The question of performance is an other thing - but what is performance? Speed? Resource profile?
Making a query complicated - if not impossible - won't help you in making it performing. In such cases you can better optimize your code's resource consumption when using a stored procedure.

Hi Raja Shekar,

 I assume you have a table Orders with following data.

    ITEM   ORDERNO   QTY
    --------------------
 X   ORdx    10
 X   Ordy    20
 X   Ordx    30
 Y   Ordx    20
 Y   Ordy    30
 X   OrdX    40
 X   OrdZ    50
 Z   ORdZ    100
 Y   Ordzy   8
 Y   OrdXy   9
 X   Ordxys  10

If you want to get a result set like the following,

     ITEM     QTY
   -----------------
     X    60
     Y    50
     X    90
     Z   100
     Y    17
     X    10

then try the following query on table Orders

SQL
WITH OrderCTE As (
 
   SELECT  ROW_NUMBER() OVER(ORDER BY (SELECT 1)) RowNum, ITEM,QTY FROM ORDERS
)
,ORDERQTYCTE AS
(
 
 SELECT  TOP 1 0 AS RowNumber,ITEM as Item,CAST(0 as Real) as Qty, 0 OrderLevel 
 FROM OrderCTE  
 
 UNION ALL
 
 SELECT RowNumber+1 AS RowNumber, OrderCTE.ITEM As Item, 
 (CASE WHEN OrderCTE.ITEM = ORDERQTYCTE.Item THEN ORDERQTYCTE.QTY+OrderCTE.QTY
 ELSE OrderCTE.QTY  END) AS Qty, 
 CASE WHEN OrderCTE.ITEM <> ORDERQTYCTE.Item THEN OrderLevel+1 
 ELSE OrderLevel END As OrderLevel
 FROM OrderCTE INNER JOIN ORDERQTYCTE 
 ON ORDERQTYCTE.RowNumber = OrderCTE.RowNum - 1
 
)
 
SELECT  Item,MAX(QTY) QTY FROM ORDERQTYCTE
GROUP BY OrderLevel,Item ORDER BY OrderLevel



Here have used CTE, Recursive CTE to get the desired result set.

I hope this solution helps you. Happy coding. :)
 
Share this answer
 
v3
Comments
damodara naidu betha 11-Jun-13 7:37am    
what is the data type of the "Qty" column in your table ? I have used "int" for this column in my table
Raja Sekhar S 11-Jun-13 7:40am    
it's Real.... Thanks For the Quick Reply....
Raja Sekhar S 11-Jun-13 7:55am    
Thank you Damodara Naidu... It's Working..... +5 for your Answer... Can u Suggest Where i can i learn about Recursive CTE's...
damodara naidu betha 11-Jun-13 7:47am    
I have changed query according to your "Qty" columns's data type. Now it is running fine in my machine. Please let me know the status. If it is running fine then remove your first comment, please.
Raja Sekhar S 11-Jun-13 7:59am    
It's Running Fine.... Deleted....
Revised after comment added to Solution 4 by OP (Raja Sekhar S):

SQL
SELECT SumKey,Item,Sum(Qty) FROM table_y GROUP BY SumKey,Item ORDER BY SumKey,Item
 
Share this answer
 
v6
Comments
RelicV 10-Jun-13 9:56am    
OP is asking about consecutive rows, not all the records. The n+3th record has Item X and it should not be included.
Mike Meinz 10-Jun-13 10:06am    
I think the Item X in the n+3 position in the example is a typo. I think the OP meant Z.

Neverthless, the definition of consecutive rows is unclear in the example provided in the question. We can't depend on the order of rows in a table to make decisions. When free space is re-used, inserted rows are not necessarily in a physical order that matches the chronological order.
Raja Sekhar S 11-Jun-13 1:34am    
Thanks For the Reply Mike...
But this is not the Answer... i want the sum of Item X From 1 to 'n'... but i don't want 'n+3'..
I want the sum of Qty of Item X For only Consecutive Rows having Item x...
(+5 For your Answer...)
+5 for the answer.....
In the Exanmple Which i stated..... i want the sum of Qty of Item X From i to 'n' (i.e.. OrderZx to orderX).. But i don't want to include Orderc(i.e n+3 Row) Which Will be added if i use your Query...
If i use Your Query the output Will be 10+20+100+...+300+10 But i want Only this 10+20+100+...+300 as Output... The Definition of Consecutive Rows Here is: Only the rows Having Item X as Continously... Like...
Row1 ItemX Qty
Row2 ItemX Qty
Row3 ItemX Qty
Row4 ItemX Qty
Row5 ItemX Qty
Row6 ItemY Qty
Row7 ItemY Qty
Row8 ItemX Qty

in the Above Example The Consecutive rows having ItemX are 5 Rows...
So I want the sum of Qty For Five Rows.. ie.. Row1(Qty)+Row2(Qty)+Row3(Qty)+Row4(Qty)+Row5(Qty).... But i Don't want to include Row8(Qty)...
Hope This Gave u the Definiton of Consecutive Rows in this Particular Criteria....
Mike Meinz 11-Jun-13 6:33am    
It is still unclear how consecutive rows are defined. You cannot rely on the physical order of rows in the table to make decisions. You must specify columns to be used in an ORDER BY or GROUP BY or some other method to select the rows to be processed from table_y. I still do not understand why ItemX for OrderC is not to be included. Just saying you don't want that one order's item X included does not explain why. Knowing why will help to define the correct algorithm to use.
Raja Sekhar S 11-Jun-13 8:21am    
+5 For the Answer Sir... as a Token of Respect sir...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900