Hi I have below code as
var query = (from R in db.Registrations
join c in db.Campus
on R.CampusId equals c.CampusId
from tsr in db.TutorStudentRequests.Where(t => t.TutorId == R.RegistrationId).DefaultIfEmpty()
where R.UserTypeId == 2 && tsr.StatusId!=3
orderby R.Name ascending
select new
{
RegistrationId = R.RegistrationId,
Name = R.Name,
Email = R.Email,
Phone = R.Phone,
Password = c.CampusName,
IsGPA = R.IsGPA,
IsActive = R.IsActive,
StripeId = R.StripeId,
CreatedOn = R.CreatedOn,
UserTypeId =tsr.StudentReviewRating
})
.ToList();
I have Registration table having single row and I also have another table TutorStudentRequests which have multiple rows. How can I get average of column name StudentReviewRating present in TutorStudentRequests table?
Structure may be seem as:
Registration Table
RegistrationId Name Email
1 abc abc#gmail.com
2 xyz xyz#gmail.com
TutorStudentRequests Table
Id TutorId(RegistrationId of F.k.) StudentReviewRating
1 1 5
2 1 2
3 1 1
4 2 3
I want UserTypeId data as average of StudentReviewRating for each TutorId
Tried
var query = (from R in db.Registrations
join c in db.Campus
on R.CampusId equals c.CampusId
from tsr in db.TutorStudentRequests.Where(t => t.TutorId == R.RegistrationId).DefaultIfEmpty()
where R.UserTypeId == 2 && tsr.StatusId != 3
group R by new
{
R.RegistrationId,
R.Name,
R.Email,
R.Phone,
c.CampusName,
R.IsGPA,
R.IsActive,
R.StripeId,
R.CreatedOn,
} into groupings
select new
{
RegistrationId = groupings.Key.RegistrationId,
Name = groupings.Key.Name,
Email = groupings.Key.Email,
Phone = groupings.Key.Phone,
Password = groupings.Key.CampusName,
IsGPA = groupings.Key.IsGPA,
IsActive = groupings.Key.IsActive,
StripeId = groupings.Key.StripeId,
CreatedOn = groupings.Key.CreatedOn,
Average = groupings.Average(p=>Convert.ToDecimal(p.StudentReviewRating))
});
But it is saying Registration does not contain a definition for 'StudentReviewRating'..
What is wrong?
how about grouping by tutor, calculate the average as total ratings/number of ratings
var query = from request in data
group request by request.TutorId into groupings
let total = groupings.Sum(p=>p.StudentReviewRating)
let number = groupings.Count()
let average = (decimal)total/number
select new
{
TutorId = groupings.Key,
Summary = new
{
Total = total,
Number = number,
Average = average
}
}
and results would look like this for the given test case
TutorId Summary
1 Total 8
Number 3
Average 2.66
2 Total 3
Number 1
Average 3
Edit extra joins and extended group by
var query = from registration in registrations
join request in requests
on registration.RegistrationId equals request.TutorId
group request by new
{
registration.RegistrationId,
registration.Name,
request.TutorId,
} into groupings
select new
{
RegistrationId = groupings.Key.RegistrationId,
TutorId = groupings.Key.TutorId,
Average = groupings.Average(p=>p.StudentReviewRating)
}
Hi you can Use this to have all you want about math here
https://numerics.mathdotnet.com/
Related
How I can get unique data (*) from the table in rails based on the city
ex :- my table as bellow
id = 1 ,name = 'demo1' ,city = 'city1'
id = 2 ,name = 'demo2' ,city = 'city1'
id = 3 ,name = 'demo3' , city = 'city2'
i need output based on unique city, means output should be
id = 1 ,name = 'demo1' ,city = 'city1'
id = 2 ,name = 'demo2' ,city = 'city1'
get all records based on the city then get once with uniq name keep in mind the id is unique as auto-generated by rails
Model.where(city: 'Paris').select('DISTINCT name')
I have a detailed spreadsheet with a list of different products (about 1000 - the sheet 'Products' is a shorter example). https://docs.google.com/spreadsheets/d/1X_OGWq1SLUcPOSmcXAfzn1ySW4kOtwn2sFroAtlLpKQ/edit?usp=sharing
On the sheet IN/OUT I enter the date, the number of units, the name of the product purchased or sold (Column E to select purchased or sold.).
In column N I enter manually the Price per unit purchased. So the same product can be purchased for different prices in different dates.
I would like to get the price in column O automatically when I enter the data about the sold product. But the first purchased must be sold first. There is more explanation in the example spreadsheet.
Is it possible to do this somehow? (picture edited)
Here is a custom function
function sellPrice() {
var begin = 3
var sh = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
var currentRow = sh.getActiveRange().getRow()
var data=sh.getRange(begin,1,currentRow-begin+1,18).getValues()
if (data[currentRow-begin][4]!="Sold"){return}
var product = data[currentRow-begin][10]
var alreadySold = 0
for (var i=0;i<data.length;i++){
if (data[i][10] == product && data[i][4] == 'Sold' && i < (currentRow-begin)){
alreadySold += data[i][2]
}
}
var toBeSold = data[currentRow-begin][2]
var price = 0
data.forEach(function(row){
if (row[10] == product && row[4] == 'Purchased'){
var qty = Math.max(Math.min(row[2] - alreadySold,toBeSold),0)
alreadySold -= row[2] - qty
toBeSold -= qty
price += qty * row[13]
}
})
return (price/data[currentRow-begin][2])
}
to use it :
=sellPrice($O$1)
check / uncheck on O1 to re-calculate if necessary
I also made a comparison between FIFO and AVG with at the end the same situation. AVG offers less variations.
I'm trying to fetch the record from 3 tables by comparing the user Logged in name
Here is my code:
public ActionResult MeritList() //departmental merit listed students details with status 1
{
var username= HttpContext.Session["UserName"];
List<StdListModel> model = new List<StdListModel>();
var query = (from s in Context.tblStdDetails
join e in Context.tblStdEnrollments on s.ID equals e.StdReg_ref_id
//join d in Context.tblDepartments on e.Depart_ref_id equals d.ID
where s.Status == '1' && e.tblDepartment.DepartName == username
select new StdListModel
{
ID = s.ID,
Name = s.Name,
FatherName = s.FatherName,
CNIC = s.CNIC,
FormNo = s.FormNo,
DiaryNo = s.DiaryNo,
Status = s.Status
}).ToList();
foreach(var item in query)
{
model.Add(new StdListModel()
{
ID=item.ID,
Name=item.Name,
FatherName=item.FatherName,
CNIC=item.CNIC,
FormNo=item.FormNo,
DiaryNo=item.DiaryNo
});
}
return View(model);
}
Also Tried this Query
var query = (from s in Context.tblStdDetails
join e in Context.tblStdEnrollments on s.ID equals e.StdReg_ref_id
join d in Context.tblDepartments on e.Depart_ref_id equals d.ID
where s.Status == '1' && d.DepartName.Equals(username)
select new StdListModel
{
ID = s.ID,
Name = s.Name,
FatherName = s.FatherName,
CNIC = s.CNIC,
FormNo = s.FormNo,
DiaryNo = s.DiaryNo,
Status = s.Status
}).ToList();
But it does not return anything model=0, query =0, the database has right values and I don't get any error either.
please check username with tolower() and trim function.
e.tblDepartment.DepartName.ToLower().Trim() == username.ToLower().Trim()
or
e.tblDepartment.DepartName.ToLower().Trim().equals(username.ToLower().Trim())
I got the problem. It is in
s.Status == '1'
I just changed it into
s.Status == 1
and it works fetch the data from the database.
I have a table with the following fields:
Id Name Score Event
(1 John 2 3)
(2 John 4 3)
(3 john 5 3)
and I would like to get the following result:
(John, "2 +4+5", 11(Total score))
I'm trying to combine the results to show the sum in a string format then show the sum result.
Can anyone please help me with this issue.
Thank you,
Franciso
You need to call the toList() method before using methods like string.Format or string.Join because they are not supported by Linq to SQL.
You should modify your code into something like this:
var group = (from Classificacao in _dbSet.classificacao
from Evento in _dbSet.evento
where Classificacao.class_id_Evento == id_evento
where Evento.id_evento == id_evento
group Classificacao by new
{
Classificacao.class_atletaNome,
Classificacao.class_numAtleta,
Classificacao.class_atletaEquipa,
Classificacao.class_paisAtleta,
Evento.even_name,
Evento.local.local_nome,
Evento.compTipo.CompTipo_name
} into g).ToList()
The idea is to materialize the query into a list before calling the methods.
var model = group.Select(g => new
{
g.Key.class_numAtleta,
g.Key.class_atletaEquipa,
g.Key.class_atletaNome,
g.Key.class_paisAtleta,
class_fianlAtleta = g.Sum(c => c.class_fianlAtleta.Value),
class_classGeral = g.Min(c => c.class_fianlAtleta.Value),
class_nome = g.Key.even_name,
local_nome = g.Key.local_nome,
CompTipo_name = g.Key.CompTipo_name,
class_40ponto = ((from u in g
where u.class_id_Evento == id_evento
group u by new
{
u.class_atletaNome,
u.class_fianlAtleta
}
into k
select new
{
//Score = string.Concat(k.Key.class_fianlAtleta.ToString(), " + ", g.Key.class_atletaNome)
Score = string.Format("{0}",k.Key.class_fianlAtleta)
})).Select(c=>c.Score).FirstOrDefault()
}).OrderBy(c => c.class_fianlAtleta).ThenBy(c => c.class_classGeral)).toList();
I can't check if the code is correct therefore I leave it to you, anyway once you have your List in memory you can apply the methods supported by Linq to entity.
Here is my code:
var model = (from Classificacao in _dbSet.classificacao
from Evento in _dbSet.evento
where Classificacao.class_id_Evento == id_evento
where Evento.id_evento == id_evento
group Classificacao by new
{
Classificacao.class_atletaNome,
Classificacao.class_numAtleta,
Classificacao.class_atletaEquipa,
Classificacao.class_paisAtleta,
Evento.even_name,
Evento.local.local_nome,
Evento.compTipo.CompTipo_name
} into g
select new
{
g.Key.class_numAtleta,
g.Key.class_atletaEquipa,
g.Key.class_atletaNome,
g.Key.class_paisAtleta,
class_fianlAtleta = g.Sum(c => c.class_fianlAtleta.Value),
class_classGeral = g.Min(c => c.class_fianlAtleta.Value),
class_nome = g.Key.even_name,
local_nome = g.Key.local_nome,
CompTipo_name = g.Key.CompTipo_name,
class_40ponto = ((from u in g
where u.class_id_Evento == id_evento
group u by new
{
u.class_atletaNome,
u.class_fianlAtleta
}
into k
select new
{
//Score = string.Concat(k.Key.class_fianlAtleta.ToString(), " + ", g.Key.class_atletaNome)
Score = string.Format("{0}",k.Key.class_fianlAtleta)
})).Select(c=>c.Score).FirstOrDefault()
}).OrderBy(c => c.class_fianlAtleta).ThenBy(c => c.class_classGeral);de here
You need something like this:
var result = table
.GroupBy(t => new { t.Name, t.Event })
.ToList()
.Select(t => new
{
Name = t.Key.Name,
JoinedScores = string.Join(" + ", t.Select(group => group.Score).ToArray()),
TotalScore = t.Sum(group => group.Score).ToString() + " (Total Score)"
}).ToList();
The first call to the ToList() method is needed because Linq to SQL will not support the calls to string.Join(). I'm not sure but probably you can replace it with a call to AsEnumerable().
I have the following code which adapts linq entities to my Domain objects:
return from g in DBContext.Gigs
select new DO.Gig
{
ID = g.ID,
Name = g.Name,
Description = g.Description,
StartDate = g.Date,
EndDate = g.EndDate,
IsDeleted = g.IsDeleted,
Created = g.Created,
TicketPrice = g.TicketPrice
};
This works very nicely.
However I now want to populate a domain object Venue object and add it to the gig in the same statement. Heres my attempt....
return from g in DBContext.Gigs
join venue in DBContext.Venues on g.VenueID equals venue.ID
select new DO.Gig
{
ID = g.ID,
Name = g.Name,
Description = g.Description,
StartDate = g.Date,
EndDate = g.EndDate,
IsDeleted = g.IsDeleted,
Created = g.Created,
TicketPrice = g.TicketPrice,
Venue = from v in DBContext.Venues
where v.ID == g.VenueID
select new DO.Venue
{
ID = v.ID,
Name = v.Name,
Address = v.Address,
Telephone = v.Telephone,
URL = v.Website
}
};
However this doesnt compile!!!
Is it possible to adapt children objects using the "select new" approach?
What am I doing so very very wrong?
Your inner LINQ query returns several objects, not just one. You want to wrap it with a call like:
Venue = (from v in DBContext.Venues
where v.ID == g.VenueID
select new DO.Venue
{
ID = v.ID,
Name = v.Name,
Address = v.Address,
Telephone = v.Telephone,
URL = v.Website
}).SingleOrDefault()
Your choice of Single() vs. SingleOrDefault() vs. First() vs. FirstOrDefault() depends on what kind of query it is, but I'm guessing you want one of the first two. (The "OrDefault" variants return null if the query has no data; the others throw.)
I also agree with Mike that a join might be more in line with what you wanted, if there's a singular relationship involved.
Why are you doing a join and a sub select? You can just use the results of your join in the creation of a new Venue. Be aware that if there is not a one to one relationship between gigs and venues you could run into trouble.
Try this:
return from g in DBContext.Gigs
join venue in DBContext.Venues on g.VenueID equals venue.ID
select new DO.Gig { ID = g.ID, Name = g.Name, Description = g.Description,
StartDate = g.Date, EndDate = g.EndDate, IsDeleted = g.IsDeleted,
Created = g.Created, TicketPrice = g.TicketPrice,
Venue = new DO.Venue { ID = venue.ID, Name = venue.Name,
Address = venue.Address, Telephone = v.Telephone,
URL = v.Website }