Search code examples
sqlselectjoinsql-server-2000

Weird SQL request(Join)


Assuming there are two tables A={a,b} and B={0,1,2}, which can be joined

tableA  tableB
a       0
b       1
a       2
        3

How to get the following result ExpectingResult:

tableA  tableB
a-------0
b-------1
null----2
null----3

OR

   tableA   tableB
    a-------2
    b-------3
    null----0
    null----1

Just make sure the element in each table just appear once, I tried all kinds of join(inner, full, cross), none of them can achieve so. Could anybody give me a tip?

Thank you very much

Please check this link out to the question itself: http://www.sqlfiddle.com/#!3/9fc21/2


Solution

  • That is a crappy request. There is almost negligible reasons for producing such an output that comes to mind, although I'm not ruling out a sane reason completely.

    For SQL Server 2000, you will need to go through temp tables to get a sequential key to zip up with.

      SELECT IDENTITY(int,1,1) ID, Value
        INTO #tblA
        FROM tableA
    ORDER BY Value;
    
      SELECT IDENTITY(int,1,1) ID, Value
        INTO #tblB
        FROM tableB
    ORDER BY Value;
    
      SELECT A.Value, B.Value
        FROM #tblA A FULL OUTER JOIN #tblB B ON A.ID = B.ID
    ORDER BY Coalesce(A.ID, B.ID);