Search code examples
sqlhana

How to select data from two tables together


I have a table which is split in two parts in SAP HANA (because of memory issue):

  • "TEST"."TABLE_01"
  • "TEST"."TABLE_02"

Now I want to select some columns from each table and make the remaining as a one table.

For example if TABLE_01 and TABLE_02 have 6 columns I want to select 3 columns from each and wanted to run the query for the whole table (which will be having 3 columns from TABLE_01 and TABLE_02).

Say TABLE_01 is like

id    student_name      class    subject   marks    rank
___  _______________    _____    _______   ______   _____
 1        john            10        phy      90       3 
 2        jean            11        che      80       6 
 3        oliver          10        phy      93       2 
 4        ryan            12        mat      99       1 

like wise TABLE_02 will have this data:

   id    student_name      class    subject   marks    rank
    ___  _______________    _____    _______   ______   _____
     1        tim            10        phy      93       3 
     2        jack           11        che      82       6 
     3        steve          10        phy      93       3 
     4        isaac          12        mat      99       9 

So now I want to take id, student_name and rank.

 id    student_name          rank
___  _______________         _____   
 1        john                3 
 2        jean                6 
 3        oliver              2 
 4        ryan                1 
 1        tim                 3 
 2        jack                6 
 3        steve               3 
 4        isac                9 

I want to run the query on this table. But how to join these two tables together? Any help is appreciated.


Solution

  • Try using UNION operator:-

    The UNION operator is used to combine the result-set of two or more SELECT statements.

    Both UNION and UNION ALL concatenate the result of two different SQLs. They differ in the way they handle duplicates.

    UNION performs a DISTINCT on the result set, eliminating any duplicate rows. UNION ALL does not remove duplicates, and it therefore faster than UNION.

    Example :-

    select id, student_name, rank from table_01
    union 
    select id, student_name, rank from table_02
    

    OR

    select id, student_name, rank from table_01
    union all
    select id, student_name, rank from table_02