SQL to LINQ - Rolling months of dates - c#

Wish to convert this to LINQ.
select COUNT(*) as 'BillsOver30' from pssuite_web.pujhaccd
where billdays>30 and DATEDIFF(month,'07-07-2016', GETDATE()) <= 13
Group By Month(billdate)
This will show 13 rolling months from 07-07 with how many bills were over 30 for each month.
This is the terrible query I've written in LINQ, which doesn't work:
DateTime earliestDate = objdate1.DateStart.Value.AddMonths(-13);
var custQuery9 = ((from m in DataContext.pujhaccds
where m.billdays > 30
&& m.billdate >= earliestDate
&& m.billdate <= objdate1.DateStart
group m by m.billdays into p
select p)).Count();

To get result as you described in comments:
var result = (from m in DataContext.pujhaccds
where m.billdays > 30 &&
m.billdate >= earliestDate &&
m.billdate <= objdate1.DateStart
group m by m.billdate.Month into p
select new { Month = p.Key, Count = p.Count() }).ToList();
To get it like in original question replace the select above like this:
select p.Count()
That grouping will be problematic though if you have data from different years and want to separate it. If that is the case group by 2 fields - year and month:
var result = (from m in DataContext.pujhaccds
where m.billdays > 30 &&
m.billdate >= earliestDate &&
m.billdate <= objdate1.DateStart
group m by new { m.billdate.Value.Month, m.billdate.Value.Year } into p
select new { Date = $"{p.Key.Month} - {p.Key.Year}", Count = p.Count() }).ToList();

Related

Linq searches for recent birthdays (within 15 days)

How to use Linq
A table
Field Birthday
Linq searches for recent birthdays (within 15 days)
from a in Employee where a.PositionStatus == true select new{ a.Name,a.Birthday}
Try below query
var fromdate = DateTime.Now;
var todate = DateTime.Now.AddDays(15);
var result =
(
from a in Employee
where a.PositionStuats==true && a.DateOfBirth.Value.Month >= fromdate.Month &&
a.DateOfBirth.Value.Month <= todate.Month &&
a.DateOfBirth.Value.Day >= fromdate.Day && a.DateOfBirth.Value.Day <= todate.Day
select new{ a.Name,a.Birthday}
).ToList();
Depending on your entity frame work version you can also replace a.DateOfBirth.Value.Month with a.DateOfBirth.Month.

How to pass 2 dates in .Where?

currently in the code I am outputting the employees table which have end dates of anything from before today's date and up to 90 days. I am trying to make it so only employees with maximum -30 days and + 90 of today's date.
(Fairly new so be easy)
(NOT SURE HOW TO CORRECTLY USE 2 DATES FOR .ADDDAYS )
Thanks
public ActionResult Index()
{
var employees = db.employees;
var today = DateTime.Today.AddDays(90);
var past = DateTime.Today.AddDays(-30);
var q = db.employees.Where(t => t.EndDate <= today );
return View(q.OrderByDescending(t => t.EndDate));
}
Why can't you use a AND (&&) condition like
var q = db.employees.Where(t => t.EndDate <= today && t.EndDate >= past);
It is simple by using conditional-AND && operator & combining both queries as single line:
var q = db.employees.Where(t => t.EndDate >= past && t.EndDate <= today)
.OrderByDescending(t => t.EndDate);
return View(q);
Try following code. You can add the OrderByDescending(t => t.EndDate) on the first line of code.
var q = db.employees.Where(t => t.EndDate >= past && t.EndDate<= today)OrderByDescending(t => t.EndDate);
return view(q);

SQL query to LINQ left outer join

I need help with converting a SQL query to LINQ. I tried with Linqer but that didn't give the expected results. This is my SQL query:
SELECT
dr.startDate,
dr.endDate,
SUM(CASE WHEN me.Size <= 10 THEN 1 ELSE 0 END) AS FirstGroup,
SUM(CASE WHEN me.Size > 10 AND me.Size <= 20 THEN 1 ELSE 0 END) AS SecondGroup,
SUM(CASE WHEN me.Size > 20 AND me.Size <= 30 THEN 1 ELSE 0 END) AS ThirdGroup,
SUM(CASE WHEN me.Size > 30 THEN 1 ELSE 0 END) AS FourthGroup,
MAX(ISNULL(me.Size,0)) AS MaxSize,
SUM(ISNULL(me.Size,0)) AS SpaceTotal
FROM
time_intervals dr
LEFT OUTER JOIN Rooms me
ON ( me.DateTime BETWEEN dr.startDate AND dr.endDate)
GROUP BY
dr.startDate,
dr.endDate
ORDER BY dr.startDate
The LINQ i tried is:
var stats = from t in time_intervals
from q in query
where q.DateTime >= t.startDate && q.DateTime <= t.endDate
select new {
Date = t.startDate,
First = (q.Size <= 10),
Second = (q.Size > 10 && q.Size <= 20),
Third = (q.Size > 20 && q.Size <= 30),
Fourth = (q.Size > 30)
};
But that didn't give the same result as the SQL query.
You are not using group keyword in your LINQ while you are grouping records by by start date and end date.
Try this code:-
var stats = (from t in time_intervals
from q in query.Where(m=> m.DateTime >= t.startDate && m.DateTime <= t.endDate).DefaultIfEmpty()
group q by new { t.startDate, t.endDate, q.Size } into g
select new
{
Date = g.Key.startDate,
First = g.Count(m=>m.Size <= 10)
}).OrderBy(m => m.startDate);

How to convert nested sql statement to linq to entities?

I'm trying to create a basic room availability statement to use with linq to entity framework. I have two tables: 'Room' including columns RoomID/RoomSize and 'Booking' including BookingID/RoomID/StartDate/Enddate.
I have got a working sql statement:
SELECT RoomID, RoomSize from Room
where RoomID NOT IN (SELECT RoomID from booking
where ('08/01/2015' >= [start] AND '08/01/2015' <= [end]) OR ('08/20/2015' >= [start] AND '08/20/2015' <= [end]))
I have got this far with the linq to entity statement:
var rooms = (from r in db.Rooms
where !(((from b in db.Bookings
where (startDate >= b.StartDate && endDate <= b.EndDate) || (endDate >= b.StartDate && endDate <= b.EndDate)).Contains(r.RoomID))
select new AvailableRoom
{
ID = r.RoomID,
Size = r.RoomSize
});
I get an error at the last bracket before .Contains(r.RoomID) saying I should have a select statement but I just can't seem to get it working.
Any suggestions would be welcome.
If you reckon using lambdas would be better/easier please feel free to suggest and example. I'm just not too familiar with them myself.. yet.
Thank you.
You can use LINQ !...Any() for the SQL NOT IN(), like so :
var rooms = (from r in db.Rooms
where !db.Bookings
.Where(b => (startDate >= b.StartDate && endDate <= b.EndDate)
||
(endDate >= b.StartDate && endDate <= b.EndDate)
)
.Any(b => b.RoomID == r.RoomID)
select new AvailableRoom
{
ID = r.RoomID,
Size = r.RoomSize
});

how to select a weeks amount of dates from a database?

What I am trying to do is search my database (ado.net with linq to sql) for all entrys within the last week.
The database has a field called date and I need the entries that are 7 days previous to the current date.
var records = (from r in context.PumpInfoTables
where r.Date.Equals(DateTime.Now)
//&& where r.date <= 7 days <--help
select r);
so I am looking for some help with this query, is there a between function that can be used?
DateTime weekFromNow = DateTime.Now.AddDays(-7);
var records = (from r in context.PumpInfoTables
where r.Date < DateTime.Now
&& r.Date >= weekFromNow
select r);
This is really simple:
var oneWeekAgo = DateTime.Today.AddDays(-7);
var records = (from r in context.PumpInfoTables
where r.Date >= oneWeekAgo
select r);
This assumes that you don't have entries from the future. If you do have, use this instead:
var today = DateTime.Today;
var oneWeekAgo = today.AddDays(-7);
var records = (from r in context.PumpInfoTables
where r.Date >= oneWeekAgo && r.Date <= today + 1
select r);
Please note:
My code uses DateTime.Today instead of DateTime.Now, assuming you are only interested in the date part, not the time.
Something like this?:
var records = (from r in context.PumpInfoTables
where r.Date > DateTime.Today.AddDays(-7)
select r);

Categories