Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Is it possible to avoid cursor in this example?

$
0
0

Hello,

I have a situation where the final result is being repeated because the main condition is being passed correctly. However, the primary element shouldn't be repeated.

I've been playing around with common table expresions and the function row_number but without luck. Maybe this case has to be done using a cursor?

DECLARE @collection TABLE (b int, a int);
DECLARE @data TABLE (a int, x int);
INSERT INTO @collection(b) VALUES (101),(101),(102),(102),(102),(103),(103);
INSERT INTO @data VALUES (1,101),(2,101),(3,101),(4,102),(5,102),
(6,102),(7,102),(8,103);

SELECT col.b, ca.* FROM @collection col CROSS APPLY(
	SELECT TOP(1) a FROM @data WHERE x = col.b
	ORDER BY a ASC 
) AS ca
--SELECT b FROM @collection;SELECT * FROM @data

Running this query you will see that "a" is being repeated with the first item found by value in "b"

My expected result in the example should be:

1011
1012
1024
1025
1026
1038

Any ideas?


JaimePR,


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>