We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- SQL
- Advanced Join
- Symmetric Pairs
- Discussions
Symmetric Pairs
Symmetric Pairs
Sort by
recency
|
1546 Discussions
|
Please Login in order to post a comment
SET NOCOUNT ON;
/* Enter your query here. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. */
DECLARE @X INT; DECLARE @Y INT; DECLARE @IT INT = 1; DECLARE @IMAXX INT; DECLARE @JMAXX INT; DECLARE @LINE VARCHAR(MAX)=''; DECLARE @COUNT INT =0;
DECLARE @CTE TABLE ( RowNum INT, X INT, Y INT );
-- Populate the table variable INSERT INTO @CTE (RowNum, X, Y) SELECT ROW_NUMBER() OVER (ORDER BY X, Y) AS RowNum, X, Y FROM (SELECT DISTINCT X, Y FROM FUNCTIONS) AS DistinctFunctions; DECLARE @RESULT TABLE( X INT, Y INT )
SELECT @IMAXX=COUNT() FROM @CTE ; SELECT @JMAXX=COUNT() FROM FUNCTIONS;
WHILE @IT <= @IMAXX BEGIN DECLARE @JT INT =1; SELECT @X = X, @Y = Y FROM @CTE WHERE RowNum = @IT; WHILE @JT <= @JMAXX BEGIN IF @X <= @Y BEGIN IF @X=@Y BEGIN SELECT @COUNT=COUNT() FROM FUNCTIONS WHERE X=@Y AND Y=@X; IF @COUNT>=2 BEGIN INSERT INTO @RESULT VALUES(@X, @Y); BREAK; END END ELSE BEGIN SELECT @COUNT=COUNT() FROM FUNCTIONS WHERE X=@Y AND Y=@X; IF @COUNT>=1 BEGIN INSERT INTO @RESULT VALUES(@X, @Y); BREAK; END END END SET @JT+=1; END SET @IT+=1; END SELECT * FROM @RESULT; go
This is my solution. What I like about it is that all the conditions are in one line, so it is easy remove or add to conditions in one place. Also, the problem description isn't very clear that we should return only distict values, I had to assume that from the example and then from the multiple fail test (yes you're not alone if you run into this issue)
Good old nested queries: select f.x, f.y from (select f.x, f.y, min(f.rowid) r from functions f where f.x <= f.y group by f.x, f.y) f where exists (select 1 from functions f1 where f1.x = f.y and f1.y = f.x and f1.rowid <> f.r) order by f.x;
This question has wrong description, something that leads to wrong assumptions. One should not use X1 and X2 in example, it means X1 and X2 are adjecent data points. Instead use Xa and Xp where a and p can be any number from 1 to N, N being the size of the data set.