I have the following table:
╔════════╦════════════╗ ║ USERID ║ LANGUAGEID ║ ╠════════╬════════════╣ ║ 1 ║ 2 ║ ║ 1 ║ 7 ║ ║ 1 ║ 8 ║ ║ 2 ║ 10 ║ ║ 2 ║ 3 ║ ╚════════╩════════════╝
now I want to create all the possible pairs of languages for each user which means that I want the result set to be: for user 1: (2,7), (7,8), (2,8)
for user 2: (10,3)
to do so I've done the following query:
SELECT a.userId , a.LanguageId, b.LanguageId FROM knownlanguages a, knownlanguages b WHERE a.userID=b.userID AND a.LanguageId<>b.LanguageId
the result that i'm getting is for user 1: (2,7), (7,8), (2,8) , (7,2), (8,7), (8,2)
for user 2: (10,3), (3,10)
there is no difference for me between (10,3) and (3,10)
how can I remove the duplicate lines?
tnx
Solution. Select column values in a specific order within rows to make rows with duplicate sets of values identical. Then you can use SELECT DISTINCT to remove duplicates. Alternatively, retrieve rows in such a way that near-duplicates are not even selected.
ALWAYS put the join predicates in the join. Where clause predicates are not evaluated until after the entire result set has been generated, so unneeded rows are carried along throughout the processing, and in certain outer join scenarios, putting predicates in where clause will generate incorrect results.
To delete the duplicate rows from the table in SQL Server, you follow these steps: Find duplicate rows using GROUP BY clause or ROW_NUMBER() function. Use DELETE statement to remove the duplicate rows.
Check for Duplicates in Multiple Tables With INNER JOINUse the INNER JOIN function to find duplicates that exist in multiple tables. Sample syntax for an INNER JOIN function looks like this: SELECT column_name FROM table1 INNER JOIN table2 ON table1. column_name = table2.
With your identifiers:
SELECT a.userId , a.LanguageId, b.LanguageId FROM knownlanguages a inner join knownlanguages b on a.userID=b.userID and a.LanguageId < b.LanguageId
Testing: Fot table:
create table t ( u int, l int); insert into t values ( 1, 2), ( 1, 7), ( 1, 8), ( 2, 10), ( 2, 3);
The query is:
select t1.u, t1.l as l1, t2.l as l2 from t t1 inner join t t2 on t1.u = t2.u and t1.l < t2.l
( Results)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With