Search code examples
sqlunionsp-send-dbmail

UNION join to email the set of rows based on the unique values in one column


I am trying to make union join on two tables , The output that i want is the rows from two tables for particular unique value should appear sequentially .

For example consider below : If table A has values

C1 C2
a 1
b 2

and table B has values

C1 C2
a 5
b 7

then union should look like

C1 C2
a 1
a 5
b 2
b 7 

and also I want to email separately to some group of people, the rows in table format based on the Colum C1 values.

For e.g if where C1 =a then email those rows in email body to certain ids.


Solution

  • Try This

     create table tableA
        (
          C1 char,
          C2 int
        )
    
    
    
     create table tableB
    (
      C1 char,
      C2 int
    )
    
    insert into tablea values('a',1)
    insert into tablea values('b',2)
    insert into tableb values('a',5)
    insert into tableb values('b',7)
    
    
    
    Select * from (select * from tableA
    union
    select * from tableb)
    a
    order by A.C1,A.C2
    

    Output:

        C1  C2
    1   a   1
    2   a   5
    3   b   2
    4   b   7