简体   繁体   中英

Teradata SQL - Union and Where Clause

have a Teradata SQL UNION query and need to know how I can extract data from 2 tables where date in first part of UNION is before the date in the second part of the UNION query. Example:

Select
name1,date1
from table1
UNION
Select
name2,date2
from table2
where date2 < date1

Would like to see only records where date2 is before date1. This is just an example of what I need to retrieve from my data.

Select Pat_Name, Provider, Clinic_Encounter_Date from Clinic table UNION Pat_Name, Provider, Hosp_Encounter_Date from Hospital table where Hosp_Encounter_Date < Clinic_Encounter_Date;

My SQL query runs fine, but when I add the WHERE clause I keep getting an error message. Teradata just doesn't like me!!!

Hopefully, this is a bit more helpful. :-)

Thank you in advance for your assistance.

The SQLs in before and after the UNION are independent SQLs, so in the second statement it is not recognizing date1. ie the following statement is not valid.

Select name2,date2 from table2 where date2 < date1

You will need to change your statement to

Select
name1,date1
from table1
UNION
Select
name2,date2
from table2
where date2 < (select Min(date1) from table1)

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