Note that there are some explanatory texts on larger screens.

plurals
  1. POLINQ to SQL complex query problem
    primarykey
    data
    text
    <p>I have 3 tables: Principal (Principal_ID, Scale), Frequency (Frequency_ID, Value) and Visit (Visit_ID, Principal_ID, Frequency_ID). I need a query which returns all principals (in the Principal table), and for each record, query the capacity required for that principal, calculated as below:</p> <pre><code>Capacity = (Principal.Scale == 0 ? 0 : (Frequency.Value == 1 ? 1 : Frequency.Value * 1.8) / Principal.Scale) </code></pre> <p>I'm using LINQ to SQL, so here is the query:</p> <pre><code>from Principal p in ShopManagerDataContext.Instance.Principals let cap = ( from Visit v in p.Visits let fqv = v.Frequency.Value select (p.Scale != 0 ? ((fqv == 1.0f ? fqv : fqv * 1.8f) / p.Scale) : 0) ).Sum() select new { p, Capacity = cap }; </code></pre> <p>The generated TSQL:</p> <pre><code>SELECT [t0].[Principal_ID], [t0].[Name], [t0].[Scale], ( SELECT SUM( (CASE WHEN [t0].[Scale] &lt;&gt; @p0 THEN ( (CASE WHEN [t2].[Value] = @p1 THEN [t2].[Value] ELSE [t2].[Value] * @p2 END)) / (CONVERT(Real,[t0].[Scale])) ELSE @p3 END)) FROM [Visit] AS [t1] INNER JOIN [Frequency] AS [t2] ON [t2].[Frequency_ID] = [t1].[Frequency_ID] WHERE [t1].[Principal_ID] = [t0].[Principal_ID] ) AS [Capacity] FROM [Principal] AS [t0] </code></pre> <p>And the error I get:</p> <pre><code>SqlException: Multiple columns are specified in an aggregated expression containing an outer reference. If an expression being aggregated contains an outer reference, then that outer reference must be the only column referenced in the expression. </code></pre> <p>And ideas how to solve this, if possible, in one query?</p> <p>Thank you very much in advance!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload