Solved

Database Calculation

Posted on 2011-09-07
9
232 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
 
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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
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

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
In Microsoft Access, learn different ways of passing a string value within a string argument. Also learn what a “Type Mis-match” error is about.

743 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now