Question

I have two user SQL tables with more or less the same data in it and I want to merge the two tables and only take the user with the highest MyLevel. Maybe it makes more sense if I show what I have and what I want.

Table One:

MyName, MyDescr, MyLevel, FromDB
John, "Hey 1", 100, DB1
Glen, "Hey 2, 100, DB1
Ive, "Hey 3, 90, DB1

Table Two:

MyName, MyDescr, MyLevel, FromDB
John, "Hey 4", 110, DB2
Glen, "Hey 5", 90, DB2
Ive, "Hey 6", 90, DB2

What I want to archieve (ignore the <--):

MyName, MyDescr, MyLevel, FromDB
John, "Hey 4", 110, DB2
Glen, "Hey 2, 100, DB1
Ive, "Hey 6", 90, DB2 <-- doesn't matter which one as it is the same level

Of course it is possible, but I am really in the dark regarding JOINs and especially when needing to GROUP it or alike?

Was it helpful?

Solution

You can use CASE for each column after you have made a join:

SELECT 
    COALESCE(t1.MyName COLLATE DATABASE_DEFAULT, t2.MyName )  AS MyName
    ,CASE WHEN t2.MyLevel > t1.MyLevel THEN t2.MyDescr COLLATE DATABASE_DEFAULT ELSE t1.MyDescr   END AS MyDescr
    ,CASE WHEN t2.MyLevel > t1.MyLevel THEN t2.MyLevel ELSE t1.MyLevel END AS MyLevel
    ,CASE WHEN t2.MyLevel > t1.MyLevel THEN t2.FromDB COLLATE DATABASE_DEFAULT ELSE t1.FromDB  END  AS FromDB
FROM TableOne t1  
FULL JOIN TableTwo t2 ON t1.MyName = t2.MyName COLLATE DATABASE_DEFAULT

SQLFiddle DEMO

Edited for collation conflicts. I have used COLLATE DATABASE_DEFAULT but you can also choose to use specific collation - ie COLLATE Danish_Norwegian_CI_AS. You can use COLLATE on either side of operation.

OTHER TIPS

The problem is that you're trying to say that one string is more than the other.

To compare the numeric value, you'll have to convert these to numbers somehow. A good start would be to use substr(yourfieldname, n) to cut of the text. Then you can use convert to typecast it to int; convert(int, substr(nbr, 3)) <= 10

You can then just join and select the max of these values.

You have the chance to be in SQL Server, and to be able to use analytic query.
Just do an union of the two tables, and seek the maximum by Level :

SELECT *
FROM
(
  SELECT *,
         ROW_NUMBER() OVER (PARTITION BY MYNAME ORDER BY MYLEVEL DESC) as Rank
  FROM
  (
    SELECT * FROM TableOne t1  
    UNION
    SELECT * FROM TableTwo t2
  ) tUnion
) tRank
WHERE RANK = 1

Note that you need to use ROW_NUMBER instead of RANK to avoid duplicates ranking.

SQLFiddle Demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top