简体   繁体   中英

SQL - Joining same table

Let's say I have a table Applications as follows

ApplicationId INT,
CustomerId INT,
ApplicationDate DATETIME,
IsNewCustomer BOOL

I would like to retrieve a list of applications for a given day along with the IsNewCustomer flag (which is set if no applications are present for the given CustomerId.

Currently I am using a join on the same table as follows

select 
    o.ApplicationId as ApplicationId,
    cast(o.ApplicationDate as date) as ApplicationDate,
    case when n.ApplicationID is not null then 1 else 0 end as IsNewCustomer,
    row_number() over (partition by o.ApplicationId order by o.ApplicationDate desc) as AppSeqNum
from 
    Applications o 
    left join Applications n 
        on n.CustomerId = o.CustomerId
        and n.ApplicationDate < o.ApplicationDate
where
    AppSeqNum = 1
    and ApplicationDate = getdate()

I was wondering if there is a better way of achieving the same without having to join on the same table as it doesn't 'feel' like the most elegant solution.

Thanks!

Well, you might use a sub query, but that will just disguise your self join. There is nothing inherently wrong with self joins, they can just get out of hand if you dont have the right indexes and constraints and the table size is limited. One of the reasons you might have heard that self joins are bad is the problem of finding breaks in an otherwise continous monotonic sequence. Say you have a thousand values, with 5 missing and you do a self join (with no indexes or constraints) on value = value +1 then the query optiiser may well decide that there are 1000*1000 possible rows before trying to find the 5 null matches. So if you have a reasonably limited resuts set then no problem.

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