I’ve been banging my head on this one for a while now. I want to achieve this:
SELECT [t2].[nArtKey], [t2].[value] AS [nQty]
FROM (
SELECT SUM([t0].[nQty]) AS [value], [t1].[nArtKey]
FROM [vdatStockTransactions] AS [t0]
INNER JOIN [regArtSKU] AS [t1] ON [t0].[nSKU] = [t1].[nSKU]
GROUP BY [t1].[nArtKey]
) AS [t2]
INNER JOIN [regArticles] AS [t3] ON [t2].[nArtKey] = [t3].[nArtKey]
INNER JOIN [regGroupConnector] AS [t4] ON [t2].[nArtKey] = [t4].[nArtKey]
WHERE [t2].[value] > @p0
What I have so far with LINQ gives me pretty much exactly what I want, exept for the quantity…
from trans in context.vdatStockTransactions
join sku in context.regArtSKUs on trans.nSKU equals sku.nSKU
group trans by new { sku.nArtKey } into grp
where grp.Sum(g => g.nQty) > 0
join art in context.regArticles on grp.Key.nArtKey equals art.nArtKey
join ca in context.regGroupConnectors on grp.Key.nArtKey equals ca.nArtKey
select new
{
nArtKey = grp.Key.nArtKey,
//nQty = grp.Sum(g => g.nQty)
};
However, if I uncomment nQty I get this:
SELECT [t7].[nArtKey], [t7].[value] AS [nQty]
FROM (
SELECT [t3].[nArtKey], (
SELECT SUM([t5].[nQty])
FROM [vdatStockTransactions] AS [t5]
INNER JOIN [regArtSKU] AS [t6] ON [t5].[nSKU] = [t6].[nSKU]
WHERE [t2].[nArtKey] = [t6].[nArtKey]
) AS [value], [t2].[value] AS [value2]
FROM (
SELECT SUM([t0].[nQty]) AS [value], [t1].[nArtKey]
FROM [vdatStockTransactions] AS [t0]
INNER JOIN [regArtSKU] AS [t1] ON [t0].[nSKU] = [t1].[nSKU]
GROUP BY [t1].[nArtKey]
) AS [t2]
INNER JOIN [regArticles] AS [t3] ON [t2].[nArtKey] = [t3].[nArtKey]
INNER JOIN [regGroupConnector] AS [t4] ON [t2].[nArtKey] = [t4].[nArtKey]
) AS [t7]
WHERE [t7].[value2] > @p0
Why does it create that extra subquery and is there any way that I could avoid it? It makes quite a big difference in performance so I really would like to figure this out. All I want is to use the quantity ([t2].[value]) and get it into the SELECT statement.
That extra subquery only exists when there are more than one join after group by so if I remove either then the query generates the expected SQL.
NOTE: I stripped down the original query to just keep the parts that are generating this behavior so it would be easier to follow.
I haven’t tested this, but this might do the trick: