I have a table containing a list of customers, a second table containing orders placed by my customers and a third table containing the line items for the orders.
I would like to be able to use a Linq query to get the customer name, the number of orders and the total value of all the orders placed by this customer.
Assuming the following data:
[Customers]
CustomerId Name
---------------------
1 Bob Smith
2 Jane Doe
[Orders]
OrderId CustomerId
---------------------
1 1
2 1
3 2
[OrderLineItems]
LineItemId OrderId UnitPrice Quantity
--------------------------------------------
1 1 5 2
2 1 2 3
3 2 10 10
4 2 4 2
5 3 2 5
I would like the following result:
Name OrdersCount TotalValue
--------------------------------------------
Bob Smith 2 124
Jane Doe 1 10
What would be the Linq query to get this result?
If you presume that you have a strongly typed datacontext and a partial class Customer that you are free to add to, I would solve this problem like this:
public partial class Customer {
public int NumberOfOrders {
get { return Orders.Count(); }
}
public int TotalValue {
get { return Orders.OrderLineItems.Sum( o => o.UnitPrice * o.Quantity); }
}
}
YourDataContext db = new YourDataContext();
var query = from c in db.Customers
select new {c.Name, c.NumberOfOrders,
c.TotalValue}
This would project a new anonymous type with the data you requested.
Related
image
image2
Now I have like this
image3
but I want have more categories
like this
How to select many category?
Let’s say in your case, we need to define the category for every features. So feature can have many categories and inverse category can have many features. Thus, it will be a Many To Many relationships.
To accomplish this we need to create 3 tables features, categories, and intermediate table feature_category. The feature_category table will have the feature_id and category_id column which connects both feature and category table and this intermediate table called the pivot table.
Here are the table structures:
features
id - integer
name - string
categories
id - integer
name - string
feature_category
feature_id - integer
category_id - integer
=> category
id name
-- -------
1 Category 1
2 Category 2
3 Category 3
4 Category 4
=> features
id name
-- -------
1 Feature 1
2 Feature 2
3 Feature 3
4 Feature 4
=> feature_category
id feature_id category_id
-- ------- -------
1 1 1
2 2 2
3 3 2
4 3 3
4 3 4
===============================
Our feature_category table before sync() operation:
id feature_id category_id
-- ------- -------
1 1 1
2 2 2
3 2 3
4 2 4
5 3 2
6 4 3
Laravel Sync() example:
<?php
use App\Models\Feature;
$user = Feature::find(2);
// Want to keep only "Category 2" (Id 2) category
$user->category()->sync([2]);
After performing the above operation, our feature_category table will look like below:
id feature_id category_id
-- ------- -------
1 1 1
2 2 2
5 3 2
6 4 3
Checkboxes or dropdowns can be used from the frontend to select multiple categories for features and sync() method can be used to update feature cards accordingly.
First you need to create new table feature_category with two fields :
(same type of features.id) feature_id
(same type of categories.id) category_id
Second create belongsToMany relationship directly in Voyager.
Example :
Let's say i have a table structure like this :
ID | Name | SCHOOLNAME | CODESCHOOL
1 DARK Kindergarten 123 1
2 DARK Kindergarten 111 1
3 Knight NY University 3
4 Knight LA Senior HS 2
5 JOHN HARVARD 3
so, how to diplay all of the data above into like this :
ID | Name | SCHOOLNAME | CODESCHOOL
1 DARK Kindergarten 123 1
3 Knight NY University 3
5 JOHN HARVARD 3
my purpose is want to display data with the max of codeschool, but when i tried with my query below :
SELECT NAME, SCHOOLNAME, MAX(CODESCHOOL) FROM TABLE GROUP BY NAME, SCHOOLNAME
but the result is just like this :
ID | Name | SCHOOLNAME | CODESCHOOL
1 DARK Kindergarten 123 1
2 DARK Kindergarten 111 1
3 Knight NY University 3
4 Knight LA Senior HS 2
5 JOHN HARVARD 3
maybe it caused by the GROUP BY SCHOOLNAME, when i tried to not select SCHOOLNAME, the data displayed just like what i expected, but i need the SCHOOLNAME field for search condition in my query
hope you guys can help me out of this problem
any help will be appreciated
thanks
Using some wacky joins you can get a functional get max rows per category query.
What you essentially need to do is to join the table to itself and make sure that the joined values only contain the top values for the CODESCHOOL column.
I've also added a :schoolname parameter because you wanted to search by schoolname
Example:
SELECT
A.*
FROM
TABLE1 A
LEFT OUTER JOIN TABLE1 B ON B.NAME = A.NAME
AND B.CODESCHOOL < A.CODESCHOOL
WHERE
B.CODESCHOOL IS NULL AND
(
(A.SCHOOLNAME = :SCHOOLNAME AND :SCHOOLNAME IS NOT NULL) OR
(:SCHOOLNAME IS NULL)
);
this should create this output, note that dark has 2 outputs because it has 2 rows with the same code school which is the max in the dark "category"/name.
ID|NAME |SCHOOLNAME |CODESCHOOL
--| -----|----------------|----------
4|Knight|LA Senior HS | 2
5|JOHN |HARVARD | 3
2|DARK |Kindergarten 111| 1
1|DARK |Kindergarten 123| 1
It's not the most effective query but it should be more than good enough as a starting point.
Sidenote: I've been blatantly stealing this logic for a while from https://www.xaprb.com/blog/2007/03/14/how-to-find-the-max-row-per-group-in-sql-without-subqueries/
I am using an analytical window function ROW_NUMBER().
This will group (or partition) by NAME then select the top 1 CODESCHOOL in DESC order.
Select NAME,
SCHOOLNAME,
CODESCHOOL
From (
Select NAME,
SCHOOLNAME,
CODESCHOOL,
ROW_NUMBER() OVER (PARTITION BY NAME ORDER BY CODESCHOOL DESC) as rn
from myTable)
Where rn = 1;
emp_master:
empid,empname
I am having one table called as
employee_travel
travelid empid location date
1 101 abc 3/4/2014
2 102 lmn 4/4/2014
3 101 abc 5/4/2014
4 102 lmn 6/4/2014
5 101 xyz 7/4/2014
6 102 cdf 8/4/2014
now iIwant to display records employee wise like:
empid location date
101 abc --
101 abc --
101 xyz
102 lmn
102 lmn
102 cdf
I have written following query in linq:
var data = (from r in context.employee_travel
group r by new
{
r.Emp_id
} into g
select new
{
name = r.emp_master.empname,
r.date,
r.location
})
But it is giving me error on this line:
****name = r.emp_master.empname,
r.date
r.location****
Here{name is used as anonomous type in query are name of d**atatextfield of my gridview**.}
Can anyone edit my linq query to suit my needs ????
Please please please help me. I am very much new to linq so I don't know how to write this query.
from et in employee_travel
orderby et.empid
select new
{
Employee = et.Employee,
TravelRecord = et, //if you want objects
Name = et.Employee.Name,
Date = et.Date //if you want simple types
}
In that sample I chose to return the entity, but you can of course return names, dates, etc. And you can add more ordering if you need.
Or you can just get the employee_travel entity and include the employee (make sure you have the right include property name)
db.employee_travel.Include("employee").OrderBy(et=>et.empid).ToList()
NOTE
This might be a dup of this. But I don't get a clear answer from that.
The problem
I got wrong result from linq.
EXAMPLE
id groupid status name
------------------------------------
guid1 guidA reserved truck1
guid2 guidA reserved truck2
guid3 guidA reserved truck3
guid4 guidA reserved truck4
*assume all guids are guids..
**id is a primary key (unique)
CASE
If I put only where groupid == guidA the result is correct (4 rows)
but, if I put where groupid == guidA && status == reserved the result is wrong (3 rows)
EXPLANATION
The query built with expression tree. From the debug watch, the query (that return wrong the result) is like this
query.Expression:
-----------------
Convert(value(System.Data.Objects.ObjectSet`1[myEFTable]))
.MergeAs(AppendOnly)
.Where(m => ( m.groupId == value(myFilterClass).groupId))
.Where(m => m.status.Contains(value(myFilterClass).statusStr))
.Select(m => new myViewClass()
{
Id = m.id, GroupId = m.groupid, Status = m.status, Name = m.name
})
.OrderBy(o => o.Name).Skip(0).Take(10)
Then I tried to run a similar query and it returns correct result
assume e is ObjectSet<myEFTable> and strGuid is guidA
Guid grId = new Guid(strGuid);
e.AsQueryable()
.Where(m => m.status.Contains("reserved"))
.Where(m => m.groupId == grId)
.Select(m => new myViewClass()
{
Id = m.id, GroupId = m.groupid, Status = m.status, Name = m.name
}).OrderBy(o => o.Name).Skip(0).Take(10);
QUESTION
I'm completely clueless about this error..
If my EF tables are correct and the query is correct, why does it return wrong result?
Is it because the MergeAs(AppendOnly) ? because the only thing that different is that.
If this is about unique key, what should I do with myViewClass to ensure that every row is unique and should not be merged (if that was the case) ?
---------------------------------------------------------------------
UPDATE 2013/08/29
The result is incorrect because I have a typos in one of my query..
So, after changing few lot of here and there, try and error, till I almost lost the trace of whatever that changed, commented, erased, suddenly it works.. EUREKA!! what?
what I did is not really change everything, it's just a lot of changes but doesn't really end up so much different than where I was starting.. so there's that!
then that EUREKA moment ends and leave me tracing my way back to find out what is actually wrong, simply because I don't believe in miracles..
so here it is..
The tables is actually similar to this:
PartsGroups
-----------
id name
-----------
1 Nails
-----------
Items
-----------------
id name status
-----------------
2 Table Empty
5 Table Indent
6 Door Empty
3 Sofa Empty
PartsGroupPairs
------------------
id groupId partId
------------------
1 1 4
2 1 7
3 1 8
4 1 15
-------------------
Parts
------------------------
id name itemId status
------------------------
4 XNail 2 Empty
7 SNail 5 Empty
8 UNail 6 Empty
15 ZNail 3 Empty
------------------------
The relationships is like this
PartsGroups PartsGroupPairs Parts Items
----------- ------------------ ------------------------ -----------------
id name id groupId partId id name itemId status id name status
----------- ------------------ ------------------------ -----------------
1 Nails 1 1 4 4 XNail 2 Empty 2 Table Empty
1 Nails 2 1 7 7 SNail 5 Empty 5 Table Indent
1 Nails 3 1 8 8 UNail 6 Empty 6 Door Empty
1 Nails 4 1 15 15 ZNail 3 Empty 3 Sofa Empty
----------- ------------------- ------------------------ -----------------
One <---> Many Many <---> One Many <------> One
PartsGroup.pairs is a collection of PartsGroupPairs
PartsGroupPair.group is a PartsGroup
PartsGroupPair.part is a Part
Part.item is an Item
Item.parts is a collection of Parts
So when I select PartsGroup where name == 'Nails' it works perfectly, it returns 4 rows
But why when I select PartsGroup where name == 'Nails' and Status == 'Empty' it returns 3 rows?? (see below)
PartsGroups PartsGroupPairs Parts Items
----------- ------------------ ------------------------ -----------------
id name id groupId partId id name itemId status id name status
----------- ------------------ ------------------------ -----------------
1 Nails 1 1 4 4 XNail 2 Empty 2 Table Empty
1 Nails 3 1 8 8 UNail 6 Empty 6 Door Empty
1 Nails 4 1 15 15 ZNail 3 Empty 3 Sofa Empty
----------- ------------------- ------------------------ -----------------
this row didnt get selected..
PartsGroups PartsGroupPairs Parts Items
----------- ------------------ ------------------------ -----------------
id name id groupId partId id name itemId status id name status
----------- ------------------ ------------------------ -----------------
1 Nails 2 1 7 7 SNail 5 Empty 5 Table Indent
----------- ------------------- ------------------------ -----------------
the mistake I made is at the Where part. The query itself built at the runtime coz I separate entities, filters, views and paging modules. So mostly I just passing IQueryable here and there.
In the case for filter, every time I filter, I'll add another Where. So in this case it went like this below:
using(var DB = new databaseContext())
{
ObjectSet<PartsGroupPair> d =
DB.CreateObjectSet<PartsGroupPair>("partsGroupPair");
int searchGroupId = 1; // int instead of guid for example
int searchStatus = "Empty";
// filter by specific PartsGroup
IQueryable<PartsGroupPair> e = d.Where(m => m.group.id == searchGroupId);
// then if I want to filter by the status
e = e.Where(m => m.part.item.status == searchStatus)); // WRONG!!
// I want to filter by part.status, not item.status
// so instead, it should be
e = e.Where(m => m.part.status == searchStatus)); // RIGHT!!
// view
IQueryable<PartsGroupPairView> f =
e.Select(m => new PartsGroupPairView()
{
Id = m.id, GroupId = m.groupid,
Status = m.part.status, Name = m.part.name
// etc..
});
// paging
f = f.OrderBy(o => o.Name).Skip(0).Take(10);
}
The wrong filtering makes LINQ ignore the other Parts, and returns 3 rows instead of 4 because it found only one Item instead of 2 Parts.
So in my case, it's a silly typo with a quite complex data..
It's really frustrating when nothing works while everything seems to be okay..
I have two table
First table
BID Town
1 ABC
2 ABC2
3 ABC
Second Table
PID BID AmountFirst AmountSecond AmountThird Minority
1 1 1000 1000 1000 SC
2 2 2000 1000 2000 ST
3 3 1000 1000 1000 SC
BID is foreign key in Second table.
I want sum AmountFirst + AmountSecond + AmountThird for individualTown
e.g for ABC town answer should be : 6000 (summation of PID 1 and PID 2)
I want Linq query for this..Please help
Untested, but something like this should work. See hooked on linq - GroupBy operator for groupby syntax.
from bid in db.Bids
group by bid.Town into g
select new
{
Town = g.Key,
Total = g.Sum(x => x.AmountFirst + x.AmountSecond + x.AmountThird)
}
Town is now a number, you can also do:
Town = g.Key.Town