Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Database Calculation

Posted on 2011-09-07
9
Medium Priority
?
244 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

 
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 2000 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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

Did you know that more than 4 billion data records have been recorded as lost or stolen since 2013? It was a staggering number brought to our attention during last week’s ManageEngine webinar, where attendees received a comprehensive look at the ma…
The Windows Phone Theme Colours is a tight, powerful, and well balanced palette. This tiny Access application makes it a snap to select and pick a value. And it doubles as an intro to implementing WithEvents, one of Access' hidden gems.
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 …
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…
Suggested Courses

604 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