sql track在内部联接时缺少某个人的记录

时间:2018-01-13 13:05:03

标签: sql sql-server

我有一个这样的查询,但我想知道是否有更好的方法而不是下面的尝试?

列出在其CreditBalance中少于50个学分并且在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)

3 个答案:

答案 0 :(得分:2)

这只过滤范围内的交易,然后cdt.CardNo为空(因为那个加入标准)将意味着该范围内的cdt记录。

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

答案 1 :(得分:0)

您还可以在where子句中创建子查询。但它与您已经做过的几乎相同:

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) 
    )

答案 2 :(得分:0)

我喜欢在这种情况下使用#include <iostream> template<typename T> class zero_init { T val; public: zero_init() : val(static_cast<T>(0)) { std::cout << "In constructor with no parameters\n"; } T operator()() const { std::cout << "In operator()\n"; return val; } }; int main() { const zero_init<int> x; auto val = x(); return 0; }

EXISTS