I'm having a trouble getting a linq to sql query and was wondering if someone could help. I have these tables: 'Orders', 'OrderProducts', 'Products' and 'Users'. I want to get a breakdown of the count of how many products (contained in 'OrderProducts' by ProductID) each 'User' has ordered. The User's UserID is contained in the 'Orders' table and 'OrderProducts' orderID is related to the orderID in 'Orders'. Final results should be like this:
User1 User2 User3 Product1 100 75 17 Product2 24 78 18 Product3 82 48 35
So it is grouped by both UserID and ProductID and takes the sum of the qty of all grouped ProductIDs by that userID. I hope that makes sense. Any help is much appreciated, thanks!
Here's a simplified database breakdown:
Products
– ProductID
– ProductName
Orders
– OrderID
– UserID
OrderProducts
– OrderID
– ProductID
– ProductQty
Users
– UserID
– UserName
Best Answer
Here's a query that will give you a list of
Users
,Products
, and theCount
:It won't give you results in the exact format you want, but it will get you most of the way there using only Linq.
Also take note that this won't pull any extra data - (
Users
orProducts
with counts of 0). This may or may not be what you're looking for.[Edit] Here's another query to take a look at (two actually):
As is, this should give you straight results (table of ProductName, UserName, Quantity). The commented out portion will instead group by Product, which (depending on how you render your results) might be what you want.