Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql UNION same tables with additional origin column

I have two same tables. Each for each year.

  • 15_docs:

    id, name, org, slo, dok

  • 16_docs:

    id, name, org, slo, dok

Now I want to create view with UNION of both, but I need to know the rows origin.

Output VIEW:

id, name, org, slo, dok, year

How can I achieve that? I am using postgreSQL database.

like image 306
Levvy Avatar asked Dec 05 '25 14:12

Levvy


2 Answers

 SELECT id, name, org, slo, dok, 'year 2015' FROM 15_docs
UNION
 SELECT id, name, org, slo, dok, 'year 2016' FROM 16_docs

Edit

This surely works for MS SQL server, have not test it on postgresql

like image 95
apomene Avatar answered Dec 07 '25 04:12

apomene


you can use UNION & UNION ALL in this case , both give the same result because UNION clause give distinct rows at the end & UNION ALL clause combine all rows of both query result .But in this case ,this 'year' must create a uniqueness in each row . Try this query !

 SELECT 
        id,
        name,
        org,
        slo,
        dok,
        'year_15 ' as year
    FROM 
       15_docs

    UNION

    SELECT 
        id,
        name,
        org,
        slo,
        dok,
        'year_16 ' as year
    FROM 
       16_docs

or

SELECT 
        id,
        name,
        org,
        slo,
        dok,
        'year_15 ' as year
    FROM 
       15_docs

    UNION ALL

    SELECT 
        id,
        name,
        org,
        slo,
        dok,
        'year_16 ' as year
    FROM 
       16_docs
like image 28
Usman Avatar answered Dec 07 '25 03:12

Usman