473,396 Members | 1,774 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

How to sort calcuation by date and transaction id?

maheshwag
I have Confusion against utilize If,Else Statement against calculation of stock By date. And sort the same by date.

There is real challenge to calculate running total between equal date:


My Table Schema Is:
Expand|Select|Wrap|Line Numbers
  1.  
  2. TransID    int,        Auto Increment
  3. Date       datetime,
  4. Inwards    decimal(12,2)
  5. Outward    decimal(12,2)
  6.  
Suppose If I have Records as Below:

Expand|Select|Wrap|Line Numbers
  1. TransID Date(DD/MM/YYYY)  Inward        Outward     
  2.  
  3. 1       03/02/2011                        100                                       
  4. 2       12/04/2010                        200               
  5. 3       03/02/2011          400                          
  6.  
Than Result Should be:
Expand|Select|Wrap|Line Numbers
  1. TransID Date(DD/MM/YYYY)    Inward  Outward     Balance
  2.  
  3.     2         12/04/2010             200         -200          
  4.     1         03/02/2011             100         -300                                  
  5.     3         03/02/2011     400                  100           
  6.  

I wants to calculate Inward - outwards = Balance and Balance count as running total as above. but the condition that it should be as per date order by Ascending

How to sort and calculate it by date and transID?

What is transact SQL IN SQL_SERVER-2000?.
Feb 4 '11 #1

✓ answered by Rabbit

gpl, the where clause in your subquery should be
Expand|Select|Wrap|Line Numbers
  1. date < s.date OR
  2. (date = s.date AND TransID <= s.TransID)

10 2628
gpl
152 100+
SQL is not really the place to do this, it should be a function of the front end application, or report.

You could do it by a cursor, or you could use a correlated sub query to calculate the current balance by summing the columns for all rows where the date is less than or equal to the current date. Note that this can be very slow when you have more than a few rows to look at

Something like this (Ive called the table stocktable as you didnt supply a name)
Expand|Select|Wrap|Line Numbers
  1.   Select TransID,
  2.          Date, 
  3.          Inwards, 
  4.          Outward, 
  5.          (
  6.                   Select sum(inwards) - sum(outward) 
  7.                   From stocktable 
  8.                   where date <= s.date
  9.          ) as Balance
  10.  
  11.   From   stocktable s
  12.   Order by  Date,
  13.             TransID
Feb 4 '11 #2
hi,
gpl

First of all you have to use COALESCE and ISNULL function in your statement which will count any nullable.

and finally check the result of your statement which is not correct or not calculated by Ascending date.
Feb 4 '11 #3
Jerry Winston
145 Expert 100+
@maheshwag

It looks like you posted the functions to bridge gpl's code to your solution(COALESCE and ISNULL).
Is this question answered?
What was the script for your final solution?
Feb 4 '11 #4
hi
Jerry Winston,
it's not solution which is i suggested to gpl because his solution return wrong result. I just advise him to use ISNULL Or COALESCE function which is useful in this case otherwise if some columns has null value than nothing to return and ultimately your counting will get wrong.
Feb 4 '11 #5
gpl
152 100+
I fail to see how isnull/coalesce would be useful as in this case, a null does not need to be counted .. if we were using count or avg, then yes it would be necessary.

How did the results get ordered ? You requested it be sorted ascending, but the example showed it descending.

Please post your final query so I can see where I went wrong :)
Feb 6 '11 #6
Rabbit
12,516 Expert Mod 8TB
gpl, the where clause in your subquery should be
Expand|Select|Wrap|Line Numbers
  1. date < s.date OR
  2. (date = s.date AND TransID <= s.TransID)
Feb 6 '11 #7
gpl
152 100+
Rabbit
I take your point, my solution only gives a total for the day (repeated for each transID)
Nice correction
Feb 6 '11 #8
gpl

Yes the use of COALESCE OR ISNULL is usefull in your query i explain how.

if i am going to use your above query without ISNULL OR COALESCE Function than the result of out put is as below:

Expand|Select|Wrap|Line Numbers
  1. TransID Date                    InWard  Outwards Balance
  2. 3    2010-02-04 00:00:00.000     NULL     567.88      NULL
  3. 2    2011-02-06 00:00:00.000     225.66     NULL     -342.22
  4. 4    2011-02-06 00:00:00.000     NULL     115.67     -457.89
  5.  
  6.  
Now I use COALESCE OR ISNULL Funtion in my query than result should work perfectly see How?.

Expand|Select|Wrap|Line Numbers
  1. Select transID, 
  2.          Date,  
  3.          input,  
  4.          output,  
  5.          ( 
  6.                   Select sum(isnull(input,0)) - sum(isnull(output,0))  
  7.                   From stock  
  8.                   where date < s.date OR
  9.           (date=s.date AND transID <= s.transID)     
  10.          ) as Balance 
  11.  
  12.   From   stock s 
  13.   Order by  date, 
  14.             transID 
  15.  
  16.  
Now the result is:

Expand|Select|Wrap|Line Numbers
  1. transID Date                    Inwards Outwards Balance 
  2. 3    2010-02-04 00:00:00.000    NULL    567.88     -567.88
  3. 2    2011-02-06 00:00:00.000    225.66    NULL     -342.22
  4. 4    2011-02-06 00:00:00.000    NULL    115.67     -457.89
  5.  
  6.  
So if you not going to use COALESCE OR ISNULL Function in your query than Your first Nullable Columns should not return the Result/Counting of Balance Column.
Feb 7 '11 #9
hi
rabbit

Nice judge the query and Solution I am appreciate that here i solve it by another way which i would like to share with our community which is as below:

Expand|Select|Wrap|Line Numbers
  1.  
  2. select *, 
  3. cast(null as decimal(12,2)) 
  4. as balance into #trans 
  5. from stock  
  6.  
  7. -- create an index to aid performance 
  8.  
  9. create clustered index #cix_trans on #trans(date, transid)  
  10.  
  11. --set up a loop to go through all record in the temp table 
  12. --in preference to using CURSORs 
  13.  
  14. declare @date datetime, 
  15. @id int, 
  16. @balance decimal(12,2)  
  17.  
  18. select top 1 @date = date, 
  19.  
  20. @id = transid, 
  21. @balance = 0 
  22. from #trans 
  23. order by date,transid  
  24.  
  25. while @@ROWCOUNT > 0 
  26. begin   
  27. update #trans set @balance = balance = @balance + coalesce(input, -output)   
  28. where transid = @id  
  29.  
  30. -- next record 
  31.  
  32. select top 1 
  33. @date = date, 
  34. @id = transid 
  35. from #trans 
  36. where (date = @date and transid > @id) 
  37. or (date > @date) 
  38. order by date, transid 
  39. end  
  40.  
  41. -- show the output 
  42. select  
  43. transID, 
  44. date= convert(varchar,convert(datetime,date,103),103),  
  45. input,  
  46. output,  
  47. balance from #trans 
  48. order by convert(datetime,date,103), transID  
  49.  
  50. -- clean  up 
  51. drop table #trans; 
  52.  
Feb 7 '11 #10
gpl
152 100+
maheshwag
Good point, the first row would not have a current value to be subtracted from / added to without the isnull/coalesce
Feb 7 '11 #11

Sign in to post your reply or Sign up for a free account.

Similar topics

6
by: sriram | last post by:
Hi, I have been seing a weird problem with db2look tool in db2 8.2 on Windows 2000 platform. When i spool the DDL using db2look, it spools the DDL in the ascending order of database objects...
0
by: fred_stevens | last post by:
Hi all you C boffins: I need to sort a vector of doubles is ascending order. Qsort will return the sorted vector, but I need a vector of the indices of the sorted vector, not the actual sorted...
2
by: PRadyut | last post by:
In this code i tried to add the elements in ascending order but the output is only 0 1 2 the rest of the elements are not shown. the code...
2
by: Joe | last post by:
Hi, I have an asp.net script that connects to MS Access database and displays data in a table. For some reason I am do not know how to display data say in ascending order of column1. I have...
5
by: Nick Weisser | last post by:
Hi there, I'm not sure how to select the last 3 items in ascending order. This does the trick in descending order: select * from user_menu_main where deleted = 0 and hidden = 0 order by...
6
by: askmatlab | last post by:
Hello all: I would like to insert a number into a linked list in ascending order. Is the following function correct? void insert(Node **node, int v) { Node *tmp = (Node...
3
by: Eric Lilja | last post by:
Hello, consider the following assignment and my code for it: /* Write a program that does the following: * Integer numbers shall be read from a textfile and stored in a std::vector. The name...
4
by: neelesh kumar | last post by:
sir, i have a table named tblexam. i want to sort the whole table records according to the field subcode in ascending order. docmd.runsql "update tblexam order by subcode asc" But it is...
3
by: flyaway888 | last post by:
Hey. I know how to sort a list into ascending order by using a function but I need to determine whether or not the list is already sorted. Any ideas?? Thanks
6
by: flyaway888 | last post by:
Hey, I have a function that compares 2 arrays with 6 numbers in each and outputs the matching numbers. I have written a function that does this but I need to output the numbers in ascending order...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.