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')
Related
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/
how would I go about counting the number of times a string occurs in a table?
Basically I have a table that is like, say 200 entires for example (but it is larger)... each entry has a sub entry called name.
so..
itemlist[i].name == somestring.
Now I can search and find a match pretty easy using an if statment while looping though the table...
if string.find(string.lower(itemlist[i].name), string.lower(searchString)) ~= nil then
So say I'm searching for Thomas, it will return when it finds "Thomas F Malone".
The thing is some cases there are more than one result for the search value.. for example.. say there are three different names that all start with Thomas.
At the moment it will just find the 1st occurrence of the Thomas.
So the plan is to count all the occurrences of Thomas and then output all of them... but I can not work out how to get the numeric value of how many times the result is found in the table.
TL;DR - How can I count the number of occurrences that of a string in a table?
When you found the matching values, store them in a temporary table, e.g.
table.insert(temporaryTable, value)
rather than quitting the function using return. You can find below, a sample function which gathers and counts the occurence of a query string in a variable inside of a multidimensional table (or see it in action here).
--data
itemList = {
{name = "Denny Kuhlman", id = "6688"},
{name = "Russell Leisy", id = "3751"},
{name = "Hilario Stermer", id = "1886"},
{name = "Thomas Hemming", id = "9666"},
{name = "Samuel Lafuente", id = "8232"},
{name = "Lazaro Ashby", id = "5274"},
{name = "Ronnie Nicosia", id = "9664"},
{name = "Edison Seyal", id = "1344"},
{name = "Jerald Officer", id = "9497"},
{name = "Lupe Burdge", id = "266"},
{name = "Stephan Iler", id = "5968"},
{name = "Josue Stephens", id = "2128"},
{name = "Salvador Ortmann", id = "3643"},
{name = "Tony Ricker", id = "8799"},
{name = "Corey Carbone", id = "6485"},
{name = "Conrad Theberge", id = "139"},
{name = "Arnulfo Oquendo", id = "2861"},
{name = "Damien Balsley", id = "5572"},
{name = "Efren Sloop", id = "7106"},
{name = "Blair Clagon", id = "614"},
{name = "Dario Service", id = "1411"},
{name = "Paul Ashalintubbi", id = "3403"},
{name = "Felix Veal", id = "1539"},
{name = "Laurence Caskey", id = "2827"},
{name = "Will Ranallo", id = "8463"},
{name = "Thomas Brenner", id = "9599"},
{name = "Claudio Hallmark", id = "6265"},
{name = "Nolan Haslett", id = "9661"},
{name = "Lenard Pereira", id = "5652"},
{name = "Dusty Duer", id = "4034"},
}
--
function countStringOccurence(query, itemList)
query = string.lower(query)
--if query string is found, store index of the itemList in table searchResult
local searchResult = {}
for i, item in ipairs(itemList) do
local name = string.lower(item.name)
if string.find(name, query) then
table.insert(searchResult, i)
end
end
--return both the occurence count and the list of found item
return #searchResult, searchResult
end
--execute the function
count, foundItemList = countStringOccurence("thomas", itemList)
--print results
print(count) --> 2
for i, index in ipairs(foundItemList) do
print(index, itemList[index].name) --> 4 Thomas Hemming
--> 26 Thomas Brenner
end
NB: Please note that if your table/list entries might be moved around (e.g. sort), it might not be advisable to just store the array index because the references/values collected in foundItemList might become incorrect.
Just don't stop iterating over the table once you found something. Keep on going and increment a counter variable every time you find your string or put your results into a table and count its elements later.
local texts = {"a123", "b213", "a332", "d411", "a124"}
local result = {}
for i,v in ipairs(texts) do
if string.find(v, "a") then
table.insert(result, v)
end
end
print(#result)
I have a structure of three tables/entities: User (table users; columns id and name), Room (table roome; columns id and number), and RoomUser (user_room; columns id, user_id, room_id).
Now I want to retrieve all Rooms for a User with a given id. How to do this without to join Rooms?
$userId = 123;
// ...
$queryBuilder = $this->entityManager->createQueryBuilder();
$query = $queryBuilder->select('r')
->from(Room::class, 'r')
->join('r.RoomUsers', 'ru')
->where('ru.room_id = :userId') // room_id? ru.Room.id?
->setParameter('userId', $userId)
->getQuery();
$rooms = $query->getResult(Query::HYDRATE_OBJECT);
So in SQL it would be something like
SELECT *
FROM rooms
JOIN room_users ON room_users.room_id = rooms.id
WHERE user_id = 123;
How to implement this simple request with the QueryBuilder?
You can use MEMBER OF (docs) for that:
$query = $queryBuilder->select('r')
->from(Room::class, 'r')
->where(':user_id MEMBER OF r.users')
->setParameter('user_id', $userId)
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 }
I have a rather simple scenario where I have two tables in which I want to add data. They are managed with primary key/foreign key. I want to add new data into TABLE A and then retrieve the Id and insert into TABLE B.
I can certainly do it with a stored procedure, but I'm looking at trying to do it using Linq.
What is the best approach ?
I can certainly get the ID and do two separate inserts but that doesn't certainly seem to be a very good way of doing things.
db.Table.InsertOnSubmit(dbObject);
db.SubmitChanges();
Int32 id = dbOject.Id;
//Rest of the code
Any way to elegantly do this?
Do you have the relationship defined between the 2 tables in the object relational designed? If so, you can have linq take care of assigning the ID property of the second table automatically.
Example...
Table A – Order
OrderId
OrderDate
Table B – Order Item
OrderItemId
OrderId
ItemId
Code (Using LINQ-to-SQL):
Order order = new Order();
Order.OrderDate = DateTime.Now();
dataContext.InsertOnSubmit(order);
OrderItem item1 = new OrderItem();
Item1.ItemId = 123;
//Note: We set the Order property, which is an Order object
// We do not set the OrderId property
// LINQ will know to use the Id that is assigned from the order above
Item1.Order = order;
dataContext.InsertOnSubmit(item1);
dataContext.SubmitChanges();
hi i insert data into three table using this code
Product_Table AddProducttbl = new Product_Table();
Product_Company Companytbl = new Product_Company();
Product_Category Categorytbl = new Product_Category();
// genrate product id's
long Productid = (from p in Accountdc.Product_Tables
select p.Product_ID ).FirstOrDefault();
if (Productid == 0)
Productid++;
else
Productid = (from lng in Accountdc.Product_Tables
select lng.Product_ID ).Max() + 1;
try
{
AddProducttbl.Product_ID = Productid;
AddProducttbl.Product_Name = Request.Form["ProductName"];
AddProducttbl.Reorder_Label = Request.Form["ReorderLevel"];
AddProducttbl.Unit = Convert.ToDecimal(Request.Form["Unit"]);
AddProducttbl.Selling_Price = Convert.ToDecimal(Request.Form["Selling_Price"]);
AddProducttbl.MRP = Convert.ToDecimal(Request.Form["MRP"]);
// Accountdc.Product_Tables.InsertOnSubmit(AddProducttbl );
// genrate category id's
long Companyid = (from c in Accountdc.Product_Companies
select c.Product_Company_ID).FirstOrDefault();
if (Companyid == 0)
Companyid++;
else
Companyid = (from Ct in Accountdc.Product_Companies
select Ct.Product_Company_ID).Max() + 1;
Companytbl.Product_Company_ID = Companyid;
Companytbl.Product_Company_Name = Request.Form["Company"];
AddProducttbl.Product_Company = Companytbl;
//Genrate Category id's
long Categoryid = (from ct in Accountdc.Product_Categories
select ct.Product_Category_ID).FirstOrDefault();
if (Categoryid == 0)
Categoryid++;
else
Categoryid = (from Ct in Accountdc.Product_Categories
select Ct.Product_Category_ID).Max() + 1;
Categorytbl.Product_Category_ID = Categoryid;
Categorytbl.Product_Category_Name = Request.Form["Category"];
AddProducttbl.Product_Category = Categorytbl;
Accountdc.Product_Tables.InsertOnSubmit(AddProducttbl);
Accountdc.SubmitChanges();
}
catch
{
ViewData["submit Error"] = "No Product Submit";
}