查询以使客户在8月份处于活动状态,并在9月份在SQL中处于非活动状态

时间:2015-10-08 12:17:42

标签: sql sql-server sql-server-2008-r2

请帮助我找到在8月15日活跃的客户(在交易方面)并在SEP 15中处于非活动状态。

查询花了超过45分钟。亲切帮助..

    SELECT DISTINCT C.CustomerCode--,x.CustomerCode
    FROM Customer.Customer(nolock) c
    INNER JOIN Customer.Card (nolock)cd ON c.CustomerId=cd.CustomerId
    INNER JOIN Trans.vwValidRawTransactions  rt (nolock) ON rt.AccountNumber=cd.CardNumber AND rt.AccountTypeId=3
    where c.CustomerCode not in (
        SELECT DISTINCT ca.customercode
         FROM Customer.customer Ca (nolock)
         INNER JOIN Customer.Card cd (nolock) ON ca.CustomerId=cd.CustomerId
         INNER JOIN trans.vwValidRawTransactions ra (nolock) ON cd.CardNumber=ra.AccountNumber AND ra.AccountTypeId=3 AND ra.IsLive=1
         WHERE Ra.TransactionDate>='01-09-2015' AND Ra.TransactionDate <'01-10-2015'  ) 

 and  rt.TransactionDate>='01-08-2015' and rt.TransactionDate<'01-09-2015'

3 个答案:

答案 0 :(得分:0)

尝试使用between

SELECT DISTINCT C.CustomerCode,
       x.CustomerCode
FROM   Customer.Customer(NOLOCK) c
       INNER JOIN Customer.Card (NOLOCK)cd
            ON  c.CustomerId = cd.CustomerId
       INNER JOIN Trans.vwValidRawTransactions rt(NOLOCK)
            ON  rt.AccountNumber = cd.CardNumber
            AND rt.AccountTypeId = 3
WHERE  c.CustomerCode NOT 
       IN (SELECT DISTINCT ca.customercode
           FROM   Customer.customer Ca(NOLOCK)
                  INNER JOIN Customer.Card cd(NOLOCK)
                       ON  ca.CustomerId = cd.CustomerId
                  INNER JOIN trans.vwValidRawTransactions ra(NOLOCK)
                       ON  cd.CardNumber = ra.AccountNumber
                       AND ra.AccountTypeId = 3
                       AND ra.IsLive = 1
           WHERE  Ra.TransactionDate BETWEEN '01-09-2015' AND '01-10-2015')
       AND rt.TransactionDate BETWEEN '01-08-2015' AND '01-09-2015'

答案 1 :(得分:0)

您的问题有点不清楚,因为您的查询比问题要求的要复杂得多。

如果您正在查看事务表,可以使用聚合和having子句执行您想要的操作:

SELECT rt.AccountNumber
FROM Trans.vwValidRawTransactions rt (nolock)
WHERE rt.AccountTypeId = 3 AND
      rt.TransactionDate >= '2015-08-01' AND
      rt.TransactionDate < '2015-10-01'
GROUP BY rt.AccountNumber
HAVING MONTH(MAX(rt.TransactionDate)) = 8;

即,从两个月开始交易。然后选择最大日期月份为八月的客户。这些客户在8月份进行交易,但不是9月。

请注意使用ISO标准日期格式。您应该在SQL代码中使用标准日期格式。

我不确定你的其他查询应该做什么。

答案 2 :(得分:0)

试试这个

    SELECT DISTINCT C.CustomerCode--,x.CustomerCode
        FROM Customer.Customer(nolock) c
        INNER JOIN Customer.Card (nolock)cd ON c.CustomerId=cd.CustomerId
        INNER JOIN Trans.vwValidRawTransactions  rt (nolock) 
ON rt.AccountNumber=cd.CardNumber AND rt.AccountTypeId=3 AND 
    ((rt.IsLive =1 and rt.TransactionDate BETWEEN '01-08-2015' AND '01-09-2015')
 or (rt.IsLive !=1  and rt.TransactionDate BETWEEN '01-09-2015' AND '01-10-2015'))