I have the following SQL view:
Code:
SELECT dbo.Course.CourseId,
dbo.Course.Date,
dbo.UserDetail.Name AS 'CustomerName',
dbo.Product.Name AS 'ProductName',
COUNT(dbo.CourseDelegate.UserId) AS 'DelegateCount'
FROM dbo.Course
INNER JOIN dbo.Product ON dbo.Course.ProductCode = dbo.Product.ProductCode
LEFT JOIN dbo.UserDetail ON dbo.Course.CustomerId = dbo.UserDetail.UserId
LEFT JOIN dbo.CourseDelegate ON dbo.Course.Courseid = dbo.CourseDelegate.CourseId
GROUP BY Course.CourseId, Course.[Date], UserDetail.Name, Product.Name
And the following code is generated by ES, to page and sort the data:
Code:
WITH [withStatement] AS
(
SELECT DISTINCT c.[CourseId],c.[Date],c.[CustomerName],c.[ProductName],c.[DelegateCount],
ROW_NUMBER() OVER( ORDER BY CustomerName ASC) AS ESRN
FROM [vwCourseSummary] c
)
SELECT * FROM [withStatement] WHERE ESRN BETWEEN 1 AND 15
To cut a long(ish) story short, it's not working. The resulting data is always sorted by the first column (CourseId). It appears that the DelegateCount column (the COUNT() in the view) is the source of the problem. If I remove the DelegateCount column from the second SQL statement (i.e. the ES generated statement), everything works fine. As soon as the DelegateCount column is re-introduced, sorting breaks.
Does anyone have any idea why this is happening? Why does the introduction of an aggregate function in the view cause the sorting to break? Is this a bug with SQL Server? How can I fix / work around this problem?
Thanks
Leigh