如何为每个客户返回单个交易

时间:2014-01-09 09:59:47

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

我创建了一个Crystal Report,它使用SQL Server上的存储过程返回在给定时间范围内进行事务处理的所有卡。

我打算只识别卡是否已被使用,然后返回该卡所做的最后一行(交易)。这意味着我每张卡只返回一行,无论进行了多少次交易。

但是,当我创建报告时,我的输出如下所示:

enter image description here

我的存储过程如下所示:

ALTER PROCEDURE [dbo].[RptCardUseDateRange]
    -- Add the parameters for the stored procedure here
    @DateStart datetime,
    @DateEnd datetime

AS

BEGIN

SELECT 
    PK_Customer,
    dbo.getCustomerFullName(PK_Customer) AS FullName,
    CardNumber,
    NRTransactions,
    SchemeName,
    DateOfLastTransaction,
    TransactionDate

FROM 
    [Card] C 
    INNER JOIN CardStatus CS ON C.FK_CardStatus = CS.PK_CardStatus
    LEFT JOIN Customer CU ON C.FK_Customer = CU.PK_Customer
    INNER JOIN [User] U ON CU.FK_User = U.PK_User
    INNER JOIN [Scheme] S ON CU.FK_Scheme = S.PK_Scheme
    INNER JOIN [Transaction] T ON C.PK_Card = T.FK_Card

WHERE
    TransactionDate BETWEEN @DateStart AND @DateEnd

ORDER BY PK_Customer desc, CardNumber 

END

所以我的问题是,我应该添加什么才能每个卡号返回一行?

从我看过的其他帖子中,我知道它是这样的:

cross apply(select top 1 PK_Transaction From [Transaction] T where T.FK_Card = C.PK_Card) X

但这没有做任何事情,因为我怀疑我把错误的参数放进去了。

2 个答案:

答案 0 :(得分:1)

您需要找到每张卡的MAX交易日期并获取这些记录

    WITH Data(PK_Customer,FullName, CardNumber, NRTransactions, SchemeName, TransactionDate)
AS
(
    SELECT 
        PK_Customer,
        dbo.getCustomerFullName(PK_Customer) AS FullName,
        CardNumber,
        NRTransactions,
        SchemeName,
        DateOfLastTransaction,
        TransactionDate

    FROM 
        [Card] C 
        INNER JOIN CardStatus CS ON C.FK_CardStatus = CS.PK_CardStatus
        LEFT JOIN Customer CU ON C.FK_Customer = CU.PK_Customer
        INNER JOIN [User] U ON CU.FK_User = U.PK_User
        INNER JOIN [Scheme] S ON CU.FK_Scheme = S.PK_Scheme
        INNER JOIN [Transaction] T ON C.PK_Card = T.FK_Card

    WHERE
        TransactionDate BETWEEN @DateStart AND @DateEnd
)

SELECT d.* 
FROM DATA d 
INNER JOIN (
            SELECT CardNumber, MAX(TransactionDate) AS TransactionDate 
            FROM DATA 
            GROUP BY CardNumber
            ) md ON d.CardNumber=md.CardNumber and d.TransactionDate = md.TransactionDate
      ORDER BY d.PK_Customer desc, d.CardNumber 

答案 1 :(得分:0)

找到答案。

this帖子,看起来我很傻,过于复杂。

我必须在SELECT中将TransactionDate更改为min(TransactionDate),然后将其余内容分组以创建:

Group By PK_Customer, CardNumber, NRTransactions, SchemeName, DateOfLastTransaction