Solved

Database Calculation

Posted on 2011-09-07
9
235 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
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
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 32

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 32

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 32

Author Closing Comment

by:PowerEdgeTech
ID: 36576520
Thanks.
0

Featured Post

Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

Question has a verified solution.

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

Suggested Solutions

I originally created this report in Crystal Reports 2008 where there is an option to underlay sections. I initially came across the problem in Access Reports where I was unable to run my border lines down through the entire page as I was using the P…
Overview: This article:       (a) explains one principle method to cross-reference invoice items in Quickbooks®       (b) explores the reasons one might need to cross-reference invoice items       (c) provides a sample process for creating a M…
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…
In Microsoft Access, learn the trick to repeating sub-report headings at the top of each page. The problem with sub-reports and headings: Add a dummy group to the sub report using the expression =1: Set the “Repeat Section” property of the dummy…

839 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