I want to create a view:CREATE MyViewASSELECT Col1, Col2, [ChildRecordCount] = CASE WHEN MyChildRowCount = 0 THEN NULL ELSE CONVERT(varchar(20), MyChildRowCount) + ' Child record' + CASE WHEN MyChildRowCount = 1 THEN '' ELSE 's' ENDFROM MyTable AS T JOIN ( SELECT SomePkID, [MyChildRowCount] = COUNT(*) FROM MyChildTable AS C GROUP BY SomePkID ) AS C ON C.SomePkID = T.SomePkID
I don't like the fact that I cannot reference T.SomePkID inside the inner nested Query (out of scope) as it feels like the nested query may be inefficient.I can't (I presume?) use the Nested Query in the outser SELECT's assignment to [ChildRecordCount] as I would need it multiple times.I was wondering if I could use a [MyChildRowCount] = COUNT(*) OVER(PARTITION BY C.SomePkID)
somehow that would be more efficient ...... or something else perhaps?Thanks