Question

is it possible to order by dynamically created column like this (i want sort by AreaPriority, but with this query i get error invalid column name: AreaPriority, when i run this query in SQL Server Managment Studio everything works fine but in petapoco it runs error). Here is this select query:

SELECT strGet.StrengthId as AreaId, strGet.[Description] as AreaName,
(SELECT SUM(ias.Score) FROM ImprovementAreaScore ias WHERE ias.StrengthId=strGet.StrengthId) as AreaPriority
FROM
{0}.Strength strGet
WHERE
strGet.[Description] like '%' + @0 and strGet.SelfAssessmentId=@1 and strGet.IsStrength=0 and strGet.ToImprovementProject=1 ORDER BY AreaPriority", ...
Was it helpful?

Solution

It's strange to get different results because PetaPoco it's only running the query through ADO.net, but you can solve the problem ordering by the expression (not the column name) as was done in older SQL versions:

SELECT strGet.StrengthId as AreaId, strGet.[Description] as AreaName,
(SELECT SUM(ias.Score) FROM ImprovementAreaScore ias WHERE ias.StrengthId=strGet.StrengthId) as AreaPriority
FROM
{0}.Strength strGet
WHERE
strGet.[Description] like '%' + @0 and strGet.SelfAssessmentId=@1 and strGet.IsStrength=0 and strGet.ToImprovementProject=1 
ORDER BY (SELECT SUM(ias.Score) FROM ImprovementAreaScore ias WHERE ias.StrengthId=strGet.StrengthId)",

OTHER TIPS

I am pretty sure you cannot put a sub-select in the column list.

You should do a JOIN....

SELECT 
    strGet.StrengthId as AreaId, 
    strGet.[Description] as AreaName, 
    SUM(ias.Score) as AreaPriority

FROM {0}.Strength strGet

JOIN ImprovementAreaScore as ias ON ias.StrengthId=strGet.StrengthId

WHERE
    strGet.[Description] like '%' + @0 
and strGet.SelfAssessmentId=@1 
and strGet.IsStrength=0 
and strGet.ToImprovementProject=1 

ORDER BY AreaPriority", ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top