Three-table query data in SQL Server

I have 3 tables named tbl_monday, tbl_tuesdayand tbl_wednesdaywhich consist of the following data:

tbl_monday

id    empid   Plan
---------------------
1     6       Mon_27
2     6       Mon_27
3     6       Mon_27

tbl_tuesday

id    empid   Plan
--------------------
1     6       Tue_28
2     6       Tue_28
3     6       Tue_28     

tbl_wenesday

id  empid     Plan
------------------
1     6       Wed_29
2     6       Wed_29
3     6       Wed_29

Is there an easy way to get this result?

empid    Plan
----------------------
6       Mon_27
6       Tue_28
6       Wed_29
+4
source share
2 answers

You can query using unionbetween the three tables that would provide unique results from all queries:

SELECT empid, [plan] FROM tbl_monday
UNION
SELECT empid, [plan] FROM tbl_tuesday
UNION
SELECT empid, [plan] FROM tbl_wednesday

SQLFiddle

+5
source

It was easy to use union all:

select *
from
(
    select top 1 empid, plan
    from tbl_monday
    order by id
) m

union all

select *
from
(
    select top 1 empid, plan
    from tbl_tuesday
    order by id
) t

union all

select *
from
(
    select top 1 empid, plan
    from tbl_Wednesday 
    order by id
) w

Although it looks like you should redefine your database design.

+1
source

Source: https://habr.com/ru/post/1599812/


All Articles