Fabiano L
Fabiano L

Reputation: 3

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!

Upvotes: 0

Views: 52

Answers (2)

JERRY
JERRY

Reputation: 1173

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".

Upvotes: 0

sticky bit
sticky bit

Reputation: 37472

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;

Upvotes: 2

Related Questions