Solved

Database Calculation

Posted on 2011-09-07
9
236 Views
Last Modified: 2012-05-12
Hello,

I'm sure this will be a quick and easy one for you guys ...

I have a very simple database that stores the price of a commodity and the date that price was reported.  What I need to do is display the date and price (which I have already done), but I need to also display the difference between the current price and the previous price.  So, this week (9/7), it is 12.23, last week (8/31) it was 12.02, and the week before (8/24) it was 12.15.  I need to know how to display it like this:

9/7/11     $12.23     +$0.21     +1.75%
8/31/11   $12.02      -$0.13      -1.07%
8/24/11   $12.15     +$0.18     +2.11%

Where the difference and percentage is calculated based on the date and price.

I have the following code in the webpage to return the Price and Date:

	cmdSelect= New OleDbCommand( "SELECT * From OREO", objConn)
	dtrReader= cmdSelect.ExecuteReader()
	While dtrReader.Read()
		Response.Write(dtrReader("CurrentPrice") & " - " & dtrReader("PriceDate") & "<br>")
	End While

Open in new window


I am using Access for the database.

Thanks!
0
Comment
Question by:PowerEdgeTech
9 Comments
 
LVL 16

Expert Comment

by:carsRST
ID: 36499196
Few options...

1.  Create an Access query with the calcs in it.  Then just run your Select statement against the query.
2.  Or calculate in the SQL Statement.
3.  Do calcs in .NET

then just format the output in .NET as a percent.
0
 
LVL 17

Expert Comment

by:OriNetworks
ID: 36499218
It your change your select statement to sort in descending order you can calculate the differences easily. You need to store the previous value and compare to the next result. Something along the lines of
cmdSelect= New OleDbCommand( "SELECT * From OREO", objConn)
	dtrReader= cmdSelect.ExecuteReader()
Dim tempVal as Double = 0.00

	While dtrReader.Read()

		Response.Write(dtrReader("CurrentPrice") & " - " & dtrReader("PriceDate") 
If tempVal=0.00 Then
Response.Write("none<br />")
Else
Response.Write((tempVal-Convert.ToDouble(dtrReader("CurrentPrice"))).ToString() & "<br />")
End If	

'set the new value
tempVal = Convert.ToDouble(dtrReader("CurrentPrice"))

End While

Open in new window

0
 
LVL 17

Expert Comment

by:OriNetworks
ID: 36499250
I'm sure there are simpler ways but if you wanted to sort with most recent at the top you could put the data in a datatable and manipulate through there. Below is something along the lines of what you might do to move the data into a datatable first then loop through each row to calculate, again there are easier ways to do this.
Dim dt As New DataTable()
        dt.Columns.Add(New DataColumn("date"))
        dt.Columns.Add(New DataColumn("amount"))
        dt.Columns.Add(New DataColumn("diff"))
        dt.Columns.Add(New DataColumn("diffp"))

        Dim TempVal As Double = 0.0

        While myReader.Read()
            Dim newRow As DataRow = dt.NewRow()
            newRow("date") = myReader("date")
            newRow("amount") = myReader("amount")
            dt.Rows.Add(newRow)
        End While

        For Each dr As DataRow In dt.Rows
            If TempVal <> 0.0 Then
                dr("diff") = (Convert.ToDouble(dr("diff")) - TempVal).ToString()
            End If

            TempVal = dr("amount")
        Next

Open in new window

0
Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

 
LVL 18

Expert Comment

by:lludden
ID: 36499399
You can do it all in a query.

You need to get two adjacent rows into the same row, then perform the calculations.

SELECT T1.Date, T1.Product, T1.Price, T2.Price, T1.Price-T2.Price AS PriceChange,( (T1.Price / T2.Price)-1 ) * 100 AS ChangePercent
FROM Tt1 AS  T1  LEFT OUTER  JOIN Tt1 AS T2  ON  T2.Date < T1.Date  AND  T1.Product = T2.Product
WHERE T2.Date = (SELECT MAX(Date) FROM tt1 WHERE Product = T1.Product AND Date < T1.Date)

This works for a table with the design:
Date <DateTime>
Product <Text>
Price <Currency>
0
 
LVL 33

Author Comment

by:PowerEdgeTech
ID: 36499464
Thanks Ori ... it is giving me the differences now, but with 16 decimal places ... how can I chop the display down to 2 decimal places?  And to calculate the percentage using tempVal?  I've tried a few things, but none of them have worked.

Thanks.
0
 
LVL 17

Accepted Solution

by:
OriNetworks earned 500 total points
ID: 36524550

Dim dt As New DataTable()
        dt.Columns.Add(New DataColumn("date"))
        dt.Columns.Add(New DataColumn("amount"))
        dt.Columns.Add(New DataColumn("diff"))
        dt.Columns.Add(New DataColumn("diffp"))

        Dim TempVal As Double = 0.0

        While myReader.Read()
            Dim newRow As DataRow = dt.NewRow()
            newRow("date") = myReader("date")
            newRow("amount") = myReader("amount")
            dt.Rows.Add(newRow)
        End While

        For Each dr As DataRow In dt.Rows
            If TempVal <> 0.0 Then
                dr("diff") = Math.Round((Convert.ToDouble(dr("diff")) - TempVal).ToString(),2)
                dr("diffp") = ((Convert.ToDouble(dr("diff")) / TempVal) * 100).ToString() & "%"
            End If

            TempVal = dr("amount")
        Next

Open in new window

0
 
LVL 33

Author Comment

by:PowerEdgeTech
ID: 36524660
Hi ... thanks Ori!

I get the following when running the page:

 Overload Error
0
 
LVL 17

Expert Comment

by:OriNetworks
ID: 36573229
change
dr("diff") = Math.Round((Convert.ToDouble(dr("diff")) - TempVal).ToString(),2)

to
dr("diff") = Math.Round(CDbl((Convert.ToDouble(dr("diff")) - TempVal).ToString()),2)
0
 
LVL 33

Author Closing Comment

by:PowerEdgeTech
ID: 36576520
Thanks.
0

Featured Post

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

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

Describes a method of obtaining an object variable to an already running instance of Microsoft Access so that it can be controlled via automation.
Access developers frequently have requirements to interact with Excel (import from or output to) in their applications.  You might be able to accomplish this with the TransferSpreadsheet and OutputTo methods, but in this series of articles I will di…
Learn how to number pages in an Access report over each group. Activate two pass printing by referencing the pages property: Add code to the Page Footers OnFormat event to capture the pages as there occur for each group. Use the pages property to …
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

730 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