I have three tables:
products purchased (RecordEntered as A)
products sold in the country (SoldInCountry as B)
products sold outside the country (SoldOutCountry as C)
Each record in A could be:
entered and not yet sold
entered and sold only in the country
entered and sold only out of the country
entered and sold in the country and also outside the country
I started grouping the pieces in table B like so:
SELECT
A.IdRecord, A.Qty, sum(isnull(B.Qty,0)) AS Expr1
FROM
RecordEntered AS A
LEFT OUTER JOIN
SoldInCountry AS B ON A.IdRecord = B.IdRecord
group by A.IdRecord, A.Qty
But I do not know how to go on.
I would like a query to show me how many pieces I still have in stock.
Like this:
A.Qty - (SUM(ISNULL(B.Qty, 0)) + SUM(ISNULL(C.Qty, 0)))
I wrote an example in SQL, but the goal is LINQ:
from a in _ctx.....
where .....
select...
thanks
It isn't easy to do a full outer join in LINQ (see my answer here: https://stackoverflow.com/a/43669055/2557128) but you don't need that to solve this:
var numInStock = from item in RecordEntered
select new {
item.Code,
Qty = item.Qty - (from sic in SoldInCountry where sic.IdRecord == item.IdRecord select sic.Qty).SingleOrDefault() -
(from soc in SoldOutCountry where soc.IdRecord == item.IdRecord select soc.Qty).SingleOrDefault()
};
I assumed there would only be one sold record of each type for an item, if there could be more than one, you would need to Sum the matching records:
var numInStock = from item in RecordEntered
select new {
item.Code,
Qty = item.Qty - (from sic in SoldInCountry where sic.IdRecord == item.IdRecord select sic.Qty).DefaultIfEmpty().Sum() -
(from soc in SoldOutCountry where soc.IdRecord == item.IdRecord select soc.Qty).DefaultIfEmpty().Sum()
};
Related
I have a recommendation system that uses SQL query similar to this one:
select B.* from user User1
join rating Rating1 on User1.user_id = Rating1.id and Rating1.value = 5
join product A on A.id = Rating1.product_id
join rating Rating2 on Rating2.product_id = A.id and Rating2.value = 5
join user User2 on User2.id = Rating2.user_id and User2.id <> User1.id
join rating RatingB on RatingB.user_id = User2.id and RatingB.value =5
join product B on B.id = RatingB.product_id
WHERE User1.id = 1;
This system recommends a product to a user if they didn’t buy that product yet. The recommendation is based on the rating of the product that they gave the best rating and it looks which other users also rated that product with the same rating.
How would this query look like in Cypher?
The mentioned SQL query would look something like this if it was written using Cypher:
MATCH (pA:PRODUCT)<-[r1:Rated {"rating":5}]-(n1:USER)-[r2:Rated {"rating":5}]->(pB:PRODUCT)
MATCH (n2:USER {id:1})-[r3:Rated {"rating":5}]->(pb)
WHERE n1.id != n2.id
RETURN pB;
I have a question about Linq select statement. I am new to Linq so any help will be very helpful. I did a lot of research but I still didn't manage to write down correct Linq statement.
I have this two tables and attributes:
Table Titles(title_id(PK), title) and
Table Sales(title_id(PK), qty)
where are title_id and title string values and qty is a number which represents some quantity.
I need to write a select which will take five most selling titles from this two tables.
So, I need to make sum from qty (we can have more records with the same Sales.title_id attribute) and make group by title_id and order by sum(qty) descending and then return attributes title and title_id.
How can I make suitable solution for my question?
Regards,
Dahakka
You can do group join of tables by title_id (each group g will represent all sales of joined title). Then select title description and total of sales for that title. Order result by totals, select title and take required number of top sales titles:
var query = (from t in db.Titles
join s in db.Sales on t.title_id equals s.title_id into g
select new { Title = t.title, Total = g.Sum(x => x.qty) } into ts
orderby ts.Total descending
select ts.Title).Take(5);
Resulting SQL will look like:
SELECT TOP (5) [t2].[title] AS [Title], [t2].[value] AS [Total]
FROM (
SELECT [t0].[title_id], (
SELECT SUM([t1].[qty])
FROM [Sales] AS [t1]
WHERE [t0].[title_id] = [t1].[title_id]
) AS [value]
FROM [Titles] AS [t0]
) AS [t2]
ORDER BY [t2].[value] DESC
Following is the linq query in method syntax
sales.GroupBy(s=>s.title_id)
.Select ( x =>
new {
Title_id = x.Key,
Sales= x.Sum (x=> x.qty)
})
.OrderByDescending(x=>x.Sales).Take(5)
.Join( titles,
sale=>sale.Title_id,
title=> title.title_id,
(sale, title)=> new
{
Title = title.Title,
TotalSales=sale.Sales
}
);
I'm having problems running a LINQ query between two tables and returning an answer set that doesen't match.
TB_AvailableProducts
-Prod_ID
-Name
....
TB_Purchases
-Cust_ID
-Prod_ID
Is there a way to get all distinct products that a customer has not purchased by using 1 LINQ query, or do I have to be doing two separate queries, 1 for all products and 1 for purchased products, and compare the two?
This query will return all products, which do not have related record in purchases table.
int customerID = 1;
var query = from ap in context.TB_AvailableProducts
join p in context.TB_Purchases.Where(x => x.Cust_ID == customerID)
on ap.Prod_ID equals p.Prod_ID into g
where !g.Any()
select ap;
I don't think you need Distinct here if you don't have duplicated records in your products table.
Generated SQL query will look like:
SELECT ap.Prod_ID, ap.Name
FROM TB_AvailableProducts AS ap
WHERE NOT EXISTS (SELECT
1 AS C1
FROM TB_Purchases AS p
WHERE (1 = p.Cust_ID) AND (ap.Prod_ID = p.Prod_ID)
)
I have two tables in the database one contains a list of all possible grocery values. For Example
Milk
Cheese
Bread
Meat
the second table contains Items from Grocery that are selected. For Example:
Milk
Cheese
I want a result that has all possible grocery items with Milk and Cheese selected.
Any ideas?
Here are the tables.
The GroceryList Table:
ID INT PK
Description Varchar(50)
The ShoppingList Table:
ID INT PK
GroceryListID int FK to GroceryList.ID
So the resulting Entity would be all items from GroceryList and if they exist in ShoppingList then selected is marked as true:
ShoppingList.ID
Grocerylists.Description
Selected
Based on understanding you can do something like this
//first get the list of product which satisfy your condition
var ids = (from p ShoppingList
select p.GroceryListID ).ToList();
//second filter the Grocery products by using contains
var myProducts = from p in GroceryList
where ids.Contains(p.ID)
Select p;
or
if you want to get info about join than this image would help you
Inner Join
Outer Join
Try to understand and which may help you to resolve your query
Edit: Still sounds like you want to do a left join. In your case:
var LINQResult = from g in Datacontext.GroceryList
from s in DataContext.ShoppingList
.Where(c=>c.ID == g.ID)
.DefaultIfEmpty()
select new {
g.ID,
g.Description,
s.ID // Will be null if not selected.
};
For more examples:
Left Join on multiple tables in Linq to SQL
I have 2 tables which in simplified form look like this:
Products(
id: int,
name: varchar
);
ProductSpecs(
product_id: int,
spec_name: varchar,
spec_value: int
);
Now I need to sort products (in linq to sql) by value of some specification item (eg. "price"). So I do something like this
var products = from p in db.Products
from ps in p.ProductsSpecs
where ps.spec_name == "price"
orderby ps.spec_value
select p;
The problem is that if there's no such ProductSpec with spec_name "price" the product is not included at all. I can add these products with Union or Concat but this way the sorting of the first part is not preserved.
What is the best way to deal with this?
Thanks.
First, I would recommend that you either do this in pure SQL as a function or Stored Procedure and then access this through linq, or add a price column to your product table. It seems like price would be a normal attribute to add to all of your products even if that price is NULL.
SQL:
select p.*
from products p
left outer join productspecs ps on
p.id = ps.product_id
and ps.spec_name = 'Price'
order by ps.spec_value
With that said, here's the weird bit of LINQ that should work on your table (I might have some of the column names spelled incorrectly):
var products = from p in db.Products
join ps in (from pss in db.ProductSpecs
where pss.spec_name== "Price"
select pss
) on p.id equals ps.product_id into temp
from t in temp.DefaultIfEmpty()
orderby t.spec_value
select p;
I tested this on some tables setup like above and created 5 products, three with prices in different value orders and this LINQ ordered them just like the SQL above and returned the null result rows as well.
Hope this works!
In ordinary SQL, you'd use an LEFT OUTER JOIN. This preserves rows that appear in the left-hand table (the one listed first), even when there's no matching row in the right-hand table (the second one listed, and the one that is outer joined). You end up with nulls for the values that should be, but weren't, present in the right-hand table. So, the price for those items missing a price would appear as NULL.
What that translates to in LINQ to SQL is another matter.
You might care to think about whether it is reasonable to have products that do not have a price. You're emulating something called EAV - Entity, Attribute, Value - tables, and they are generally regarded as 'not a good thing'.
Can you not just do a simple join?
var products =
from p in db.Products
join ps in db.ProductSpecs on p.id equals ps.product_id
where ps.spec_name == "price"
orderby ps.spec_value
select p;