简体   繁体   中英

sql track lack of record for a certain person upon inner join

I have a query that goes this way but I am wondering if there is a better way to do rather than the below attempt?

List the credit balance of all members who have less than 50 credits in their CreditBalance and have not done any transactions in the year 2018 .

SELECT m.CreditBalance
FROM Member m 
INNER JOIN CreditCard cc
ON m.MemberID=cc.MemberID
INNER JOIN CreditDebitTrans cdt
ON cc.CardNo=cdt.CardNo
WHERE (cdt.TransDateTime  != DATEPART(Year,2018) 
AND
m.CreditBalance<50)

This filters only on the transactions in the range, then the cdt.CardNo is null (since that's the join criteria) will means there's on cdt records in that range.

SELECT m.memberid, m.CreditBalance
FROM Member m 
INNER JOIN CreditCard cc
ON m.MemberID=cc.MemberID
LEFT OUTER JOIN CreditDebitTrans cdt
ON cc.CardNo=cdt.CardNo and cdt.TransDateTime>='2018-01-01' and cdt.TransDateTime<'2019-01-01'
WHERE cdt.CardNo Is Null and m.CreditBalance<50
group by m.memberid, m.CreditBalance

What you can also do is to create a subquery in the where clause. But it is almost the same what you already did:

SELECT 
    m.CreditBalance
FROM 
    Member m 
WHERE   
    m.CreditBalance<50
    AND m.MemberID NOT IN (
        SELECT 
            cc.MemberID
        FROM
            CreditCard cc
        INNER JOIN      
            CreditDebitTrans cdt
        WHERE   
            cdt.TransDateTime = DATEPART(Year,2018) 
    )

I like to use EXISTS in this type of situation.

SELECT m.CreditBalance
FROM Member m
WHERE
    m.CreditBalance < 50
    -- There are no transactions for the member in 2018:
    AND NOT EXISTS (
        SELECT 1
        FROM CreditCard cc
            INNER JOIN CreditDebitTrans cdt ON cdt.CardNo = cc.CardNo
        WHERE cc.MemberID = m.MemberID
            AND cdt.TransDateTime >= '2018-01-01'
            AND cdt.TransDateTime < '2019-01-01'
    );

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