C# Expressions.How to get Sum (Amount) for last month? - c#

I hava a Transaction datatable with "Amount" field.
I want to get Sum (Amount) for 7 days
How can I do it in C# expression?
Thank you

I assume your transaction table is called 'Transaction' and have a 'Date' field;
DateTime lastWeek = DateTime.Now.Subtract(new TimeSpan(7,0,0,0));
var amountSumLastWeek = (from t in Transaction
where t.Date >= lastWeek
select t.Amount).Sum();
EDIT: Of course const in C# means compile time constant and TimeSpan does not have optional parameters, so I have update the code

Related

UTC in DB confusion when querying in linq from Web API server

I can really use some help wrapping my head around a problem I'm having querying data according to a SQL Date field.
I am storing the Date in UTC format using the following code:
objFitCalendarDto.Day = objFitCalendarDto.Day.ToUniversalTime();
That line assigns the date to the model that is inserted into the db through Entity Framework.
Now, my query is supposed to retrieve a row based on a date. So, I should be able to get the row for today, tomorrow, yesterday, and so on.
To do this, I'm using the method to search between two dates, a start date and an end date as follows:
DateTime dayBegin = DateTime.Today.Date.AddDays(dayOffset);
DateTime dayEnd = DateTime.Today.Date.AddDays(dayOffset + 1);
The purpose of dayOffset is to specify which day. If Offset is 0, then I am searching for Today. If dayOffset is 1, then I am searching for rows with tomorrow's date.
Now, since I stored the data originally in UTC, I am assuming that I must search for it in UTC as well. So before executing my query, I convert the dates to UTC like so:
dayBegin = TimeZoneInfo.ConvertTimeToUtc(dayBegin);
dayEnd = TimeZoneInfo.ConvertTimeToUtc(dayEnd);
Then I execute my query like so:
var query = (from f in Db.FitCalendars
where f.FitProgramId == programId &&
f.DayAsDate >= dayBegin && f.DayAsDate < dayEnd
select f);
problem is, it doesn't work. I have a row with the date, "2016-01-26" when I look at it in SQL Manager. However, it only returns from a query on yesterday's date. Today is 2016-01-26, by the way. Clearly I'm not getting this UTC concept. Can anyone see what I'm doing wrong here? I was assuming that if I stored everything as UTC and then before querying I converted my dates for the query to UTC, that everything should work.
UPDATE
Let's try like this:
As soon as you are storing only date part (SQL 'date' type), you
need to compare also only dates.
Instead of
DateTime dayBegin = DateTime.Today.Date.AddDays(dayOffset);
dayBegin = TimeZoneInfo.ConvertTimeToUtc(dayBegin);
let's just do
DateTime dayBegin = DateTime.UtcNow.Date.AddDays(dayOffset);
dayBegin in that case will be date with time anyway (time is 12:00:00 AM). It means, we need to truncate it with DbFunctions. We need equality check here.
var query = (from f in Db.FitCalendars
where f.FitProgramId == programId &&
f.DayAsDate == DbFunctions.TruncateTime(dayBegin)
select f);
END OF UPDATE
I believe that problem is that you comparing dates with times. In your case you need to compare only dates, as far as I understand. As a solution - use DbFunctions TruncateTime function. It can be used within linq queries - like in your code.
https://msdn.microsoft.com/en-us/library/system.data.entity.dbfunctions.truncatetime(v=vs.113).aspx
So, complete solution would be
var query = (from f in Db.FitCalendars
where f.FitProgramId == programId &&
DbFunctions.TruncateTime(f.DayAsDate) >= DbFunctions.TruncateTime(dayBegin) && DbFunctions.TruncateTime(f.DayAsDate) < DbFunctions.TruncateTime(dayEnd)
select f);

Simple.Data subtract days from date time in where clause

I am using Simple.Data (version 0.19.0.0) against a SQL Server back end database and would like a query such as the one below to take 25 days from a date to compare against the date now;
DateTime dtNow = DateTime.Now.Date;
var pool = db.Pools.FindAll(db.Pools.Status == 1
&& db.Pools.EndDate - 25 > dtNow)
.Select(db.Pools.AllColumns());
I have tried using DATEADD but get an error that the function is not recognised, I guess because the column name is not the first parameter of the method.
Is this kind of thing possible in Simple.Data, or should I ignore the date in the query and perform the check in a foreach loop following?
Thanks in advance.
Try like that;
DateTime dtNow = DateTime.Now.AddDays(-25).Date;
var pool = db.Pools.FindAll(db.Pools.Status == 1
&& db.Pools.EndDate > dtNow)
.Select(db.Pools.AllColumns());
I overcame the problem by using a where clause on my query with a >= and < date range as suggested in how to search by date question.

How to select a data access database filtering with the months of the date?

I want to select the row of a database when the month of a date is accurate. for the year I did it:
select * from table where YEAR(date)='2015' it works well for the years
for the months I made :
select * from table where Month(date)='01'// I have the date format dd/mm/yyyy
thanks
From MONTH FUNCTION;
The Microsoft Access Month function returns the month (a number from 1
to 12) given a date value.
You should check it with an integer, not a string like;
select * from table where Month(date) = 1
Try this
select * from table where Month(date)='01' and YEAR(date)='2015'

Get records of last week adding by datetime in database

I'm using asp.net MVC in my project. My database table includes some records. The table has datetime column for records. I want to get records of last week adding. So the LastlyRecords is:
DateTime.Now = 04.04.2015
LastWeekDateTime = 28.04.2015
LastWeekDateTime < LastlyRecords < DateTime.Now
Have a method that accepts a "Start Date" and "End Date" as parameters.
Call it with a start/end date like:
GetRecords(DateTime.Now.AddWeeks(-1), DateTime.Now);
For there, you can have a stored procedure fetch records between that date range (or do something similar for Entity Framework or whatever you're using).
You can do something similar in T-SQL via GETDATE() and DATEADD(), but it's arguably better to do the range calculation in the calling code (because it's more a business logic thing than a data access thing).
you have to write logic on your query or you can modify below as per your datetime range.
var lastweek = DateTime.Now.AddDays(7);
var records = d in db.Persons
where DateTime.Compare(lastweek, d.DateRecordColumn)
and DateTime.Compare(d.DateRecordColumn, DateTime.Now)
select d;
hope this help to resolve your query!!!
string dateTime = "01 April 2015 Wednesday 16:23";
DateTime time1 = Convert.ToDateTime(dateTime);
if (DateTime.Compare(DateTime.Now, time1) == 1 && // DateTime.Now > time1
DateTime.Compare(time1, DateTime.Today.AddDays((int)-7)) == 1 // time1 >= DateTime.Now-7days
)
{
#("True.")
}
else
{
#("False.")
}
The result is true, so it is in last week.

Week of year translation between c# and SQL

So I'm at the end of a long programming binge and I have one logical hurdle left to get over. My application presents KPIs for quote requests. The business leads have asked for these KPIs to be broken down by week, and I imagine when that is complete the request will come for a breakdown by month. I've figured this out in my SQL queries:
SELECT qpid FROM cpkpis WHERE DATEPART(ww, qpvalidfrom)=13 GROUP BY qpid;
Which will give my a list of qpids to compute a total from and provide actual primary keys for drill down.
What I can't get my head around is how to get an enumeration of weeks of the year form my C# code. I've looked the GregorianCalandar Class and specifically the GetWeekOfYear Method but I'm having trouble coming up with an enumeration of those values.
My question then is this: given a date range [lets say 2013-01-14 through 2013-04-10] how would I get an enumeration of the weeks of the year as ints between the start date and end date?
To help with with this task and the other requirements you're anticipating, you need a date table. IMHO the hardest thing to do in a database is to query data that isn't there.
You can query the date table:
Select Distinct DatePart(ww, dateField) as WeekNo
from DateTable
where dateField between '2013-01-14' and '2013-04-10';
From C#, an iterator is probably the simplest option:
public static IEnumerable<int> WeekNumbersBetween(
DateTime startDate,
DateTime endDate,
Calendar calendar = null,
CalendarWeekRule weekRule = CalendarWeekRule.FirstDay,
DayOfWeek firstDayOfWeek = DayOfWeek.Sunday)
{
if (calendar == null)
{
calendar = new GregorianCalendar();
}
DateTime week = startDate;
while (week <= endDate)
{
yield return calendar.GetWeekOfYear(week, weekRule, firstDayOfWeek);
week = week.AddDays(7);
}
}
The default values for the weekRule and firstDayOfWeek parameters should match the default settings in SQL. If your settings are different, you'll need to specify the correct values.
In T-SQL you could use something like:
DECLARE #StartDate DATE = '2013-01-14';
DECLARE #EndDate DATE = '2013-04-10';
WITH weekcte AS
(SELECT DATEADD(dd, -1, DATEADD(wk, DATEDIFF(wk, 0, #StartDate), 0)) AS DateValue
UNION ALL
SELECT DATEADD(wk, 1, DateValue)
FROM weekcte
WHERE DATEADD(wk, 1, DateValue) <= #EndDate )
SELECT DATEPART(ww, w.DateValue) AS 'Week No'
FROM weekcte AS w;

Categories