The database stores the currency exchange rate on a given day. Each day, one currency exchange value is collected and stored in the database as:
ID (int, AI) | VALUE | DATE |
---|---|---|
1 | 2.5 | 20.01.2021 |
2 | 2.7 | 21.01.2021 |
3 | 2.6 | 22.01.2021 |
If I would like to calculate the average exchange rate from the last 10 days, should I first sort the data by date and only retrieve the last 10 records when downloading the data, or is it enough to download the last 10 records from the database without sorting?
4
Answers
You can simply do in SQL Server database
Concept should be same in other relational databases.
Tables (and table expressions such as views and CTEs) in SQL represent unordered sets. To get data in a particular order, you must specify an
ORDER BY
clause.In fairly generic SQL you can do
In some RDBMSs, instead of
OFFSET
FETCH
, you use eitherLIMIT
orTOP
to achieve the same effect. You still needORDER BY
.Basically you have to sort first ( on date) and then get the last 10 values, so you’re on the right track.
You can do it in both ways.
If you’re using SQL with Dapper or ADO.NET, then you can write a query.
It should be sorted if you need the last 10 values
If you’re using EntityFrameWorkCore, you can write
I hope my answer helps 🙂