Is this query possible with linq?
SELECT
SUM([Weight]) * (SELECT TOP 1 Value FROM dbo.Prices WHERE '2020-04-02' BETWEEN [From] AND [To] AND ScrapId = CS.ScrapId), [FromCompany] ,CS.[ScrapId]
FROM [dbo].[CollectedScrap] AS CS
WHERE Date BETWEEN '2020-05-01' AND '2020-05-29' GROUP BY[ScrapId], [FromCompany]
Latest test:
content.table.Where(cs => cs.Date > from)
.Where(cs => cs.Date < to)
.GroupBy(collectedGroup => new { collectedGroup.ScrapId, collectedGroup.FromCompany})
.Select(group => new
{
total = group.Sum(c => c.Weight) * _context.Prices.Select(p => new { p.ScrapId, p.Value, p.From, p.To })
.Where(a => a.From > from)
.Where(a => a.To < to)
.Where(a => a.ScrapId == group.Select(gr => new { gr.ScrapId }).First().ScrapId)
.FirstOrDefault()
}).ToList();
There is not a direct relation between the tables. I use a subquery to get the correct price by date and multiply it with sum result of a group by query.
content.table.Join(
_context.Prices,
collectedScrap => collectedScrap.ScrapId,
price => price.ScrapId,
(collectedScrap, price) => new
{
label = collectedScrap.Scrap.Label,
date = collectedScrap.Date,
price = price.Value,
scrap = collectedScrap.Scrap.Label,
weight = collectedScrap.Weight
}
)
.Where(d => d.date > from)
.Where(d => d.date < to)
.Select(result => new
{
scrap = result.label,
weight = result.weight,
price = result.price,
total = result.price * result.weight
}).ToList();
With normal SQL I can use a condition for the join. How can I use a WHERE inside the join. Now it`s almost behaving as a Right join.(I need to limit the join to one result). ----- testing with groupjoin now
generated sql:
SELECT [collectedScrap.Scrap].[Label] AS [scrap], [collectedScrap].[Weight], [price].[Value] AS [price], [price].[Value] * [collectedScrap].[Weight] AS [total]
FROM [CollectedScrap] AS [collectedScrap]
LEFT JOIN [Scrap] AS [collectedScrap.Scrap] ON [collectedScrap].[ScrapId] = [collectedScrap.Scrap].[ID]
INNER JOIN [Prices] AS [price] ON [collectedScrap].[ScrapId] = [price].[ScrapId]
WHERE ([collectedScrap].[Date] > @__from_0) AND ([collectedScrap].[Date] < @__to_1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.