Linq To Sql - Get week day name from date - linq

Is it possible to construct a query in which I can retrieve week day name from a date into a separate column or variable?
I know I can very easily do this on .NET side but would like it to be in the query.

You can also use SqlFunctions...
var results=context.Listings
.Select(l=>System.Data.Entity.SqlServer.SqlFunctions.DateName("dw",l.modify_date));
Of course, this only works when using a SQL Server. Methods that are cross-database, would be to use EntityFunctions.DateDiff with a known date to get the number of days between whatever and a known prior sunday, then modulus 7, then convert to a string.

It is possible you will need to build your query which returns day names and then join to your result on day number
int[] dayNum={1,2,3,4,5,6,7};
var result = from d in dayNum
let dayOfWeek= (d == 1 ? "Monday" :
d==2 ? "Tuesday" :
d==3 ? "Wednesday" :
d==4 ? "Thursday" :
d==5 ? "Friday" :
d==6 ? "Saturday" :
d==7 ? "Sunday":"")
let dn = d
group d by new {dayOfWeek, dn} into dw
select new { dw.Key.dayOfWeek, dw.Key.dn};
The result of this will be

Related

How to get month name from month number in Power BI?

I have Year number and Month Number in my data.
How using DAX can I get the month name out of month number?
In SSRS its very easy. But how to achieve that using DAX?
You can use:
MonthName = FORMAT(DATE(1, [Num], 1), "MMM")
Result:
Nothing fancy, simply a reconstruction of a fake date from the month number provided, and reformat it with the FORMAT function.
Of course as an alternative you can go the old-fashioned way and write a SWITCH statement and hard-coded for the 12 months. It's up to you.
You can try this too:
Month name = FORMAT('Table'[date_column], "MMM")
If you use single quotes in 'MMM', it doesn't work. Ensure to use ""
By Use of Switch DAX function
MonthName = switch(True(),
MonthID = 1, "jan",MonthID = 2, "Feb",MonthID = 3, "March",MonthID = 4, "April",MonthID = 5, "May",MonthID = 6, "June",MonthID = 7, "july",MonthID = 8, "Aug",MonthID = 9, "Sept",MonthID = 10, "Oct",MonthID = 11, "Nov",MonthID = 12, "Dec"
)

How stock a numeric value (diff of 2 date)

I've to calculate the différence between two Dates : TODAY() and DATE_DEB_VAC.
With Oracle, it's kinda easy : TODAY()-DATE_DEB_VAC -> give the number of day between those 2 date.
But I've to do it with in an ETL (GENIO). I've a column to stock it like that :
NUMBER_DAY_DIFF (NUMBER 10) = TODAY()-DATE_DEB_VAC. But it's impossible to stock it cause it's 2 date.
How can i do this ? :(
You can try the val function of GENIO ETL
VAL(TODAY()-DATE_DEB_VAC)
this is equivalent to to_numbre in Oracle
NUMBER_DAY_DIFF (NUMBER 10) = DATEDIFF (TODAY; DATE_DEB_VAC)
Should give you what you need.

multiple group by using linq

I need return just 2 lines in my query. One line with a string Today and a number of cases closed today, on my second line I need a string Last Week and a number of cases closed on the last week.
How I group with a range date?
Sum Name
----------- ----------
12 Today
33 Last Weeb
How about this:
var caseCounts = Cases
.Where(c => c.Date == today || (c.Date >= startOfLastWeek && c.Date <= endOfLastWeek))
.GroupBy(c => c.Date == today ? "Today" : "Last Week")
.Select(g => new {
Name = g.Key, Sum = g.Count()
});
You would need to define the 3 dates (today, startOfLastWeek, endOfLastWeek) before hand, but it gives you the results you are after.
GROUP BY YEARWEEK(date) should work. Depending on your dbms, you might be able to use another function, or program your own.
http://www.tutorialspoint.com/sql/sql-date-functions.htm#function_yearweek

Printing Month Name in Linq

Is there any Inbuilt function in Linq to Print the month Name while working with LINQPAD?
I want to print the month name in the following Scenario
var query = from e in Employees
let month=e.BirthDate.GetValueOrDefault()
let birthmonth=month.ToString("MMMM")
select birthmonth;
query.Dump();
When I run this it is throwing NotSupportedException.
how to print the month name in Linq to Sql?
Rather than using ToString, try string.Format. Something like:
var query = (from e in Employees
let month = e.BirthDate.GetValueOrDefault()
let birthmonth = string.Format("{0:MMMM}", month)
select birthmonth);
query.Dump();
This seems to work from my local testing, although it is not included as part of the SQL query.
Do it in two steps, one to get the months from the database, then another using Linq-To-Objects to perform the formatting.
var birthDates = Employees.Select(e => e.BirthDate).ToList();
var query = birthDates.Select(d => d != null ? d.ToString("MMMM") : "Null");
query.Dump();
Whatever ORM you are using can't convert the string formatting part of you query into SQL that works on your database. So, doing it in two steps and using ToList to evaluate inbetween overcomes that problem.

How to query and calculate dates in the where clause of a LINQ statement?

I am having trouble with the following piece of code. Before I paste it, Let me give a bit of history on what should happen.
I have a model containing 2 fields of interest at the moment, which is the name of the order the customer placed, and the date at which he/she placed it. A pre-calculated date will be used to query the dateplaced field (and should only query the dates , and not the time). The query counts the amount of duplicates that occur in the MondayOrder field, and groups them together. Now , when I exclude the where clause which should query the dates, the query runs great. However, The goal of this query is to count the amount of orders for the following week based on the date the order has been placed.
List<string> returnlist = new List<string>();
DateTime dt = getNextWeekMondaysDate().Date;
switch (day)
{
case DayOfWeek.Monday:
{
var CountOrders =
from x in Data.EntityDB.Orders
group x by x.MondayOrder into m
let count = m.Count()
select new
{
MondayOrderItem = m.Key, Amount = count
};
foreach (var item in CountOrders)
{
returnlist.Add(item.MondayOrderItem + " : " +
item.Amount);
}
}
break;
The getNextWeekMondaysDate() method has an overload which I can use, where if I supply it a date, it will get the following Monday's date from the parameter given. The problem is though, LINQ does not accept queries such as the following:
var CountOrders =
from x in Data.EntityDB.Orders
where getNextWeekMondaysDate(x.DatePlaced.Value).Date == dt
group x by x.MondayOrder into m
let count = m.Count()
select new { MondayOrderItem = m.Key, Amount = count };
This is exactly what I must achieve. Is there any workaround for this situation?
UPDATE
Here is the exception I get when I try the 2nd query.
LINQ to Entities does not recognize the method 'System.DateTime getNextWeekMondaysDate(System.DateTime)' method, and this method cannot be translated into a store expression.
You cannot do this directly, as user-defined method calls cannot be translated to SQL by the EF query provider. The provider recognizes a limited set of .NET methods that can be translated to SQL and also a number of canonical functions as well. Anything that cannot be expressed using these methods only is off-limits unless you write your own query provider (which is only theoretically an option).
As a practical workaround, you can calculate an appropriate range for x.DatePlaced.Value in code before the query and then use specific DateTime values on the where clause.
As an intellectual exercise, note that this method is recognized by the query provider and can be used as part of the expression. So this abomination should work too:
var CountOrders =
from x in Data.EntityDB.Orders
where EntityFunctions.AddDays(
x.DatePlaced.Date.Value,
(9 - DateAndTime.DatePart(DateInterval.WeekDay, x.DatePlaced.Value)) % 7)
.Date == dt
group x by x.MondayOrder into m
let count = m.Count()
select new { MondayOrderItem = m.Key, Amount = count };
Linq to Entities doesn't know how to convert arbitrary C# methods into SQL - it's not possible in general.
So, you have to work with the methods it does understand.
In this case, you could do something like this:
DateTime weekBegin = CalculateWeekBegin( dt );
DateTime weekEnd = CalculateWeekEnd( dt );
var CountOrders =
from x in Data.EntityDB.Orders
where x.DatePlaced.Value >= weekBegin && x.DatePlaced.Value < weekEnd
group x by x.MondayOrder into m
let count = m.Count()
select new { MondayOrderItem = m.Key, Amount = count });

Resources