如何从主查询中筛选子查询结果

时间:2015-02-20 19:14:00

标签: sql sql-server

我有一个查询记录客户交易与上次交易的记录:

SELECT  t.CustomerID,
        t.ServiceID,
        t.dtCreated,
        Upgraded = CASE WHEN t.ServiceID = cp.ServiceID THEN 0 ELSE 1 END
FROM    Transactions AS t
        INNER JOIN
        (   SELECT  CustomerID,
                    ServiceID,
                    dtCreated,
                    RowNumber = ROW_NUMBER() OVER(PARTITION BY CustomerID ORDER BY dtCreated DESC)
            FROM    Transactions
            WHERE   transactiontype = 'Cust Purchase'
        ) AS cp
            ON cp.CustomerID = t.CustomerID
            AND cp.RowNumber = 1
WHERE   t.dtcreated > @startdate 
AND     t.dtcreated < @enddate
AND     t.transactiontype = 'Cust Save'

我想做的是过滤&#34; Cust Purchase&#34;或者&#34; cp&#34;用于提取在&#34; Cust Save&#34;之前发生的所有结果的表格表t中的事务类型。

现在,我获得了客户所拥有的最后一笔交易的结果&#34; Cust Purchase&#34;。但是,我想要&#34; Cust Purchase&#34;发生在&#34; Cust Save&#34;

之前

示例:

我拉:

Customer      Date Cust Save     Date Cust Purchase
1                 1/2/15             12/15/14
2                 1/2/15             12/17/14
3                 1/2/15             1/4/15(most recent)   Before save (12/18/14)
4                 1/2/15             12/18/14
5                 1/2/15             12/19/14

您将看到客户3的购买量为1/4/15。我想在cust保存之前购买最后一次。所以在这种情况下,我希望购买日期为&#39; 12/18/14&#39;

我试过了:

SELECT  t.CustomerID,
            t.ServiceID,
            t.dtCreated,
            Upgraded = CASE WHEN t.ServiceID = cp.ServiceID THEN 0 ELSE 1 END
    FROM    Transactions AS t
            INNER JOIN
            (   SELECT  CustomerID,
                        ServiceID,
                        dtCreated,
                        RowNumber = ROW_NUMBER() OVER(PARTITION BY CustomerID ORDER BY dtCreated DESC)
                FROM    Transactions
                WHERE   transactiontype = 'Cust Purchase' **and dtcreated < t.dtcreated**
            ) AS cp
                ON cp.CustomerID = t.CustomerID
                AND cp.RowNumber = 1
    WHERE   t.dtcreated > @startdate 
    AND     t.dtcreated < @enddate
    AND     t.transactiontype = 'Cust Save'

1 个答案:

答案 0 :(得分:0)

SELECT  t.CustomerID,
        t.ServiceID,
        t.dtCreated,
        MAX(cp.dtCreated) OVER (PARTITION BY t.CustomerID) as cp_dtCreated
        Upgraded = CASE WHEN t.ServiceID = cp.ServiceID THEN 0 ELSE 1 END
FROM    Transactions AS t
        INNER JOIN
        (   SELECT  CustomerID,
                    ServiceID,
                    dtCreated,
          )
            FROM    Transactions
            WHERE   transactiontype = 'Cust Purchase'
        ) AS cp
            ON cp.CustomerID = t.CustomerID
            AND cp.dtCreated < t.dtCreated
WHERE   t.dtcreated > @startdate 
AND     t.dtcreated < @enddate
AND     t.transactiontype = 'Cust Save'