根据帐户状态选择客户

时间:2013-12-19 01:38:05

标签: sql sql-server

我需要生成一个帐户状态为COLLECTIONS的客户报告,并且连续收取超过1个已收取费用。

Customer Table
=====================
CustomerID
FirstName
LastName
Email
Status (Collections)

Charge
=====================
ChargeID
CustomerID
DateCharged
Amount
ACK (Declined)

SELECT   Customer.CustomerID, Customer.FirstName, Customer.LastName, 
         Customer.Status, Charge.ChargeID, Charge.Amount, Charge.DateCharged, Charge.ACK
FROM     Customers
INNER JOIN Charge
ON Customer.CustomerID=Charge.CustomerID
AND Charge.ACK = 'Declined'

客户在发送到馆藏之前必须至少收取2笔费用。如何检查客户是否有2次拒绝?

2 个答案:

答案 0 :(得分:0)

通常情况下,我会说只需使用having子句进行聚合。

但是,您的查询表明您还需要有关拒绝的详细信息。相反,使用窗口函数来计算总下降次数:

SELECT *
FROM (SELECT c.CustomerID, c.FirstName, c.LastName, 
             c.Status, ch.ChargeID, ch.Amount, ch.DateCharged, ch.ACK,
             sum(case when ch.ACK = 'Declined' then 1 else 0 end) over
                 (partition by c.customerId) as NumDeclines
      FROM Customers c INNER JOIN
           Charge ch
           ON c.CustomerID = ch.CustomerID
    ) cc
WHERE ACK = 'Declined' and NumDeclines >= 2
ORDER BY CustomerId, DateCharged;

如果您只想要客户而不是细节,请执行以下操作:

SELECT c.CustomerID, c.FirstName, c.LastName, c.Status
FROM Customers c INNER JOIN
     Charge ch
     ON c.CustomerID = ch.CustomerID
WHERE ACK = 'Declined'
GROUP BY c.CustomerID, c.FirstName, c.LastName, c.Statu
HAVING count(*) >= 2;

答案 1 :(得分:0)

根据我的评论,这就是我完成手头任务的方式。

SELECT
*
FROM (
    SELECT
             Row_Number() OVER (PARTITION BY Customer.CustomerID ORDER BY Charge.DateCharged DESC) AS [Row],
             Customer.CustomerID, Customer.FirstName, Customer.LastName, 
             Customer.Status, Charge.ChargeID, Charge.Amount, Charge.DateCharged, Charge.ACK
    FROM     Customers
    INNER JOIN Charge ON Customer.CustomerID=Charge.CustomerID
) a
INNER JOIN (
    SELECT
             Row_Number() OVER (PARTITION BY Customer.CustomerID ORDER BY Charge.DateCharged DESC) AS [Row],
             Customer.CustomerID, Customer.FirstName, Customer.LastName, 
             Customer.Status, Charge.ChargeID, Charge.Amount, Charge.DateCharged, Charge.ACK
    FROM     Customers
    INNER JOIN Charge ON Customer.CustomerID=Charge.CustomerID
) b ON a.CustomerID=b.CustomerID
WHERE a.[Row]=b.[Row]-1
AND a.ACK = 'Declined'
AND b.ACK = 'Declined'
AND a.[Row] IN (1,2)
AND b.[Row] IN (1,2)