Question

I have the following T-SQL statement:

;WITH DataSource ([ColumnA]) AS
(
    SELECT TOP 100 [ColumnA] 
    FROM [dbo].[TEST] 
    WHERE [ColumnB] = 40 
    ORDER BY [ColumnC] DESC
)
SELECT [ColumnA]
      ,COUNT([ColumnA])
FROM DataSource
GROUP BY [ColumnA]

It is simply not returing the same result. I can not understand way, but some time the T-SQL statement in the CTE is not returning the correct values are because of this different results is produce, not each time, but sometimes (to be more accurate I am getting three different results).

If I excute only the following statement:

SELECT TOP 100 [ColumnA] 
FROM [dbo].[TEST] 
WHERE [ColumnB] = 40 
ORDER BY [ColumnC] DESC

I am getting the same results each time. And if I am using derived table there is no problems too:

SELECT [ColumnA]
      ,COUNT([ColumnA])
FROM
(
    SELECT TOP 100 [ColumnA] 
    FROM [dbo].[TEST] 
    WHERE [ColumnB] = 40 
    ORDER BY [ColumnC] DESC

) DataSource
GROUP BY [ColumnA]

Can anyone explaing why the CTE is not returning the correct results each time?

Was it helpful?

Solution 2

As Martin Smith pointed in his comment:

Is ColumnC unique? If not you will need to add a guaranteed unique column(s) to the ORDER BY to act as a tie breaker to ensure deterministic results.

There is nothing wrong with the CTE itself - the issue is I am not sorting by unique column.

OTHER TIPS

An ORDER BY is not allowed inside the CTE construct. Please see the remarks section here: MSDN. Provide the order by as part of the CTE_QUERY_DEFINITION. I am surprised SQL server even let you run it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top