SQL Query returning same value while using where 1 condition

Rewrite your query such a way:

SELECT a.*, x.cnt
FROM #temp a
CROSS APPLY (
    SELECT COUNT(VAL) AS cnt
    FROM #temp b
    WHERE a.val <= b.val
) x
--WHERE x.cnt = 1

If you uncomment the where clause you would get 333 | 1 as a result. You request a row from the outer table which doesn't have duplicates or bigger values.


You could see your inner count query

Select COUNT(VAL) from #temp b  
where a.val <= b.val;

as

(Select COUNT(VAL) from #temp b  
where 333 <= 333,222,111) = 1


(Select COUNT(VAL) from #temp b  
where 222 <= 333,222,111) = 2


(Select COUNT(VAL) from #temp b  
where 111 <= 333,222,111) = 3

Showing that only 333 from #temp a has one match, as it has only one equals to or smaller than match with the 3 values in #temp b.

This returns a count of 1 and is why the value 333 from #temp a is returned.