I have a bunch of incidences in a table that are linked to a supplier
I need to sum the serverity score for those incidences by supplier
So basicly have
supplier1: 500
supplier2: 600
How do I do this?
DataAccess.IncidentRepository().GetItems().Where(i => i.IncidentDate.Year == 2006)
Hope this helps
DataAccess.IncidentRepository().GetItems()
.Where(i => i.IncidentDate.Year == 2006)
.GroupBy(i => i.Supplier)
.Select(pGroup =>
new { Supplier = pGroup.Key,
Score = pGroup.Sum(pArg => pArg.SeverityScore) });
Related
I have the following sql query
SELECT statusId, statusName,sum(durationSeconds)/3600 as duration
FROM status
where date_local >=date
and durationSeconds > 0
group by statusId
order by duration desc;
I'm trying to do the same using EF core.
var result = await context.status
.Where(e => e.ShiftdateLocal >= date && e.Durationseconds > 0)
.Select(e => new LiveStatusProductionViewModel
{ StatusId = e.statusId, StatusName = e.statusName, Duration = e.Durationseconds / 3600 })
//.GroupBy(e => e.Duration)
.OrderByDescending(e => e.Duration)
.ToListAsync();
What am I doing wrong? How do I achieve the same result as on mysql?
You have did only half of work, added GroupBy but not added correct projection.
var result = await context.status
.Where(e => e.ShiftdateLocal >= date && e.Durationseconds > 0)
.GroupBy(e => new { e.statusId, e.statusName })
.Select(g => new LiveStatusProductionViewModel
{
StatusId = g.Key.statusId,
StatusName = g.Key.statusName,
Duration = g.Sum(x => x.Durationseconds / 3600)
})
.OrderByDescending(e => e.Duration)
.ToListAsync();
So I've got a table named Summaries, it looks like this
I need to get to sum the latest entries of TotalPieces based on CoveredDate and should be grouped by ServiceCode and queried by month
for example, ServiceCode 'A' has entries on 2020-01-01, 2020-01-02, 2020-01-03, 2020-01-31, 2020-02-01, 2020-02-28, 2020-02-29
and ServiceCode 'B' has entries on 2020-01-01, 2020-01-02, 2020-01-31, 2020-02-20, 2020-02-21,
i need to get the sum based on month, lastest entry on 'A' on January is on 2020-01-31, and 'B' has latest entry on 2020-01-31, I need to sum their 'TotalPieces', so I should get 25 + 25 = 50.
basically i need to do is
Get all the lastest entries based on CoveredDate and month/year
Sum the TotalPieces by ServiceCode
i got a working query, but this is just a workaround because i can't get it right on query.
int sum_totalpieces = 0;
foreach (var serviceCode in service_codes)
{
var totalpieces = _DbContext.ActiveSummaries.Where(acs =>
acs.CoveredDate.Date.Month == query_month
&& acs.CoveredDate.Date.Year == query_year
&& acs.service_codes == serviceCode
)
.OrderByDescending(obd => obd.CoveredDate)
.Take(1)
.Select(s => s.TotalPieces)
.ToList()
.FirstOrDefault();
sum_totalpieces += totalpieces;
}
the service_codes is just a List of string
If you guys could just get rid of the foreach block their and make it services_codes.Contains() on query, or another workaround to make the result faster that would be great. Thanks a lot.
This will do it, but I don't think it will translate to SQL and run at the server:
_DbContext.ActiveSummaries
.Where(b =>
b.CoveredDate >= new DateTime(2020,1,1) &&
b.CoveredDate < new DateTime(2020,2,1) &&
new [] { "A", "B" }.Contains(b.ServiceCode)
)
.GroupBy(g => g.ServiceCode)
.Sum(g => g.OrderByDescending(gb=> gb.CoveredDate).First().TotalPieces);
If you want to do it as a raw SQL for best performance it would look like:
SELECT SUM(totalpieces)
FROM
x
INNER JOIN
(
SELECT servicecode, MAX(covereddate) cd
FROM x
WHERE x.servicecode IN ('A','B') AND covereddate BETWEEN '2020-01-01' AND '2020-01-31'
)y ON x.servicecode=y.servicecode and x.covereddate = y.cd
I want to perform a group by in Entity Framework core with no repetitive groups.
Lets suppose I have two columns
Column A Column B
1 1
2 1
2 1
4 5
5 4
If a group by is performed for two columns Entity framework core the result is pretty obvious.
Column A Column B
1 1
2 1
4 5
5 4
But i want to perform a group by which works both ways A->B and B->A hence the result would be
Column A Column B
1 1
2 1
5 4
Any idea how to do that in Entity Framework Core?
My original attempt was to use Union
var user = _context.Transactions
.Where(p => !p.IsDeleted && (p.ReceiverUserId == userId) &&
(p.SenderUserId != null))
.Include(p => p.SenderUser)
.GroupBy(p => p.SenderUserId)
.Select(p => new TempModel { Id = p.FirstOrDefault().SenderUser.Id, User = p.FirstOrDefault().SenderUser, CreatedDate = p.FirstOrDefault().CreatedDate });
var user2 = _context.Transactions
.Where(p => !p.IsDeleted && (p.SenderUserId == userId) &&
(p.ReceiverUserId != null))
.Include(p => p.ReceiverUser)
.GroupBy(p => p.ReceiverUserId)
.Select(p => new TempModel { Id = p.FirstOrDefault().ReceiverUser.Id, User = p.FirstOrDefault().ReceiverUser, CreatedDate = p.FirstOrDefault().CreatedDate});
var finalQuery = user.Union(user2);
var finalQuery2 = finalQuery.GroupBy(p => p.Id);
var finalQuery1 = finalQuery2.OrderByDescending(p => p.FirstOrDefault().CreatedDate);
finalQuery.GroupBy(p => p.Id); <- this line gives error
You should sort these columns by descending: 4-5 => 5-4; 5-4 => 5-4;
5-5 => 5-5 and then group by or distinc by them:
var answer = db.Table.Select(x => new
{
ColumnA = x.ColumnA > x.ColumnB ? x.ColumnA : x.ColumnB,
ColumnB = x.ColumnA > x.ColumnB ? x.ColumnB : x.ColumnA
}).Distinct().ToList();
I want to calculate the average fuel consumption for every car in my table.
I have a spendforfuel table with IdCar, Odometer, Quantity fields.
Odometer field is current mileage.
Quantity are the litres consumed between the current mileage and last detected mileage.
Here is my formula:
100 / ( (MAX(Odometer) - MIN(Odometer)) / (SUM(Quantity) - FIRST(Quantity) ) )
Here is what I did:
$q = $this->db->select()
->from(array('s1' => 'spendforfuel'), array('fuel_consumption' => '100 / ( s2.odometer_sum / ( s3.quantity_sum - s4.first_quantity ) )'))
->joinLeft(array('s2' => 'spendforfuel'), 's2.IdCar = s1.IdCar', array('odometer_sum' => 'MAX(s2.Odometer) - MIN(s2.Odometer)'))
->joinLeft(array('s3' => 'spendforfuel'), 's3.IdCar = s1.IdCar', array('quantity_sum' => 'SUM(s3.Quantity)'))
->joinLeft(array('s4' => 'spendforfuel'), 's4.IdCar = s1.IdCar', array('first_quantity' => 's4.Quantity'))
->where('s4.Odometer > ?', 0)
->limit('1 ASC')
->group('s1.CarId')
->where('s1.CarId = ?', 76);
I am not sure if I have to use joins at all. Any ideas?
I have crawled over several of the various questions on Linq-to-SQL dealing with joins, counts, sums and etc.. But I am just having a difficult time grasping how to do the following simple SQL Statement...
SELECT
tblTechItems.ItemName,
SUM(tblTechInventory.EntityTypeUID) AS TotalOfItemByType
FROM
tblTechInventory
INNER JOIN
tblTechItems ON tblTechInventory.ItemUID = tblTechItems.ItemUID
GROUP BY
tblTechInventory.StatusUID,
tblTechItems.ItemName,
tblTechInventory.InventoryUID
HAVING
tblTechInventory.StatusUID = 26
Try this:
var query = from e in db.tblTechInventory
join f in db.tblTechItems on e.ItemUID equals f.ItemUID into x
from y in x
group e by new { e.StatusUID, y.ItemName, e.InventoryUID } into g
where e.StatusUID == 26
select new {
g.Key.ItemName,
TotalOfItemByType = g.Sum(e => e.EntityTypeUID)
};
I'll give it a shot...
var results = tblTechInventory
.Join(tblTechItems, i=> i.ItemUID, o => o.ItemUID, (i,o) => new {i.ItemName, o.EntityTypeUID, o.StatusUID, i.ItemName, o.InventoryUID})
.Where(o => o.StatusUID == 26)
.GroupBy(g => new {g.StatusUID, g.ItemName, g.InventoryUID}, (gr, items) => new {gr.Key.ItemName, items.Sum(i => i.EntityTypeUID)});