patternsqlMinor
SQL Query returning same value while using where 1 condition
Viewed 0 times
samewhileconditionsqlquerywherevaluereturningusing
Problem
I have created a temp table and inserted the values as given below.
On querying the below select statement I got 333 as the answer.
`Select *
from #temp a
Where 1 =(
Select COUNT(VAL)
from #temp b
where a.val
Result:
Can you please help me understand how SQL server came to this solution.
create table #temp( val int );
insert into #temp values(333);
insert into #temp values(222);
insert into #temp values(111);
On querying the below select statement I got 333 as the answer.
`Select *
from #temp a
Where 1 =(
Select COUNT(VAL)
from #temp b
where a.val
Result:
val
333Can you please help me understand how SQL server came to this solution.
Solution
Rewrite your query such a way:
If you uncomment the where clause you would get
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 = 1If 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.Code Snippets
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 = 1Context
StackExchange Database Administrators Q#257844, answer score: 6
Revisions (0)
No revisions yet.