简体   繁体   中英

Join two similar tables with some different columns

We have two tables, one showing results from a process and one showing errors or other events. Some of the columns can be combined, while others can't. There are unique columns in each table, so I can't use a UNION ALL.

For example I have the following columns (there are more but you get the idea):

EventID | DateTime | Station | ErrMsg

ResultID | DateTime | Station | MatNum | SerialNum

So the first three columns in each example table could be combined, but the others would need their own column.

The idea here is to overlay the results with the errors and order by the date/time so that we can see if there are any process steps causing errors.

I've tried different joins, unions, ect, but didn't quite get what I want.

Any thoughts?

This would technically work, if this is really how you want to have your output...

Select
EventID, DateTime, Station, ErrMsg, NULL
from Events
UNION ALL
Select
ResultID, DateTime, Station, MatNum, SerialNum
from Results

Since the first three columns have compatible data types and the others don't you'l need to separate columns for each of the incompatible columns. I'd also add a discriminator column so you can immediately tell which data source the row came from:

Select
'E' src, EventID,  DateTime, Station, NULL,   NULL,      ErrMsg
from Events
UNION ALL
Select
'R' src, ResultID, DateTime, Station, MatNum, SerialNum, NULL
from Results

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM