简体   繁体   中英

SQL Query Comparing A Date Against Multiple Returned Results From Same Table

I am facing an issue. I want to compare a date against multiple values in same table returned via SUBQUERY. The query purpose is to find addresses inserted by user -9 and they having their modified_date less than the modified_date of the address inserted by users other then -9 having address_type_id 1 which is Local address.

For example the query is

select pps_id,name
from individual_address i
where i.modified_by = -9
and i.address_type_id=1
and i.modified_date < (select modified_date from individual_address a where a.modified_by <> -9 
and a.address_type_id=1);

This query gives exception that this comparison is not possible as it is returning multiple rows. I know it's not correct. Can someone help me, how can i achieve the same?

Sample Data Example

Individual_Address
PPS_ID      MODIFIED_BY MODIFIED_DATE   ADDRESS_TYPE_ID     EMIRATES
1234        -9      15-05-2009      1         2
1234        1       15-05-2010      2         1
1234        1       15-05-2010      1         2
1900        1       15-05-2014      1         1
1900        1       15-05-2014      2         1
1900        1       10-07-2010      1         1

I want to get all records against -9 having address_type_id 1 but whose modified date is less than modified date whose users are not -9.

Thanks,

select pps_id,name
    from individual_address i
    where i.modified_by = -9
    and i.address_type_id=1
    and i.modified_date < (select MIN(modified_date) from individual_address a 
                           where a.modified_by <> -9 
                           and a.address_type_id=1);

Thing here is Address can be modified by so many users. I think you want modified_date < min(modified_date of user other than -9)

Take the max and min dates from the result only.

select pps_id,name
    from individual_address i
    where i.modified_by = -9
    and i.address_type_id=1
    and i.modified_date between (select min(modified_date) from individual_address a where a.modified_by <> -9 ) and (select max(modified_date) from individual_address a where a.modified_by <> -9 ) 
    and a.address_type_id=1);

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