简体   繁体   中英

Calculated Column Based on Condition in Other Table

I have to create a calculated column in a query (T2) based in a corresponding record in other table(T1) that attends to a certain condition, like this:

T1 - Contracts: [T1.Id] [T1.Conclusion]

T2 - Financial Entries: [T2.Id] [T2.ContractId] [ CALCULATED COLUMN returning "ok" if a record exists in T1 where ([T1.Id]=[T2.ContractId] and [T1.Conclusion] <= TODAY)]

Thank´s!

You can use a correlated subquery and EXISTS in a CASE expression.

SELECT t2.id,
       t2.contractid,
       CASE
         WHEN EXISTS (SELECT *
                             FROM t1
                             WHERE t1.id = t2.contractid
                                   AND t1.conclusion <= curdate()) THEN
           'ok'
       END
       FROM t2;

You can go ahead with simple LEFT join using below Query:

SELECT DISTINCT T2.*, T1.id
FROM T2
LEFT JOIN T1 ON T1.Id = T2.ContractId AND T1.Conclusion <= TODAY

If you get NULL in T1.id then not data exists else "OK".

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