如何选择客户最近的购买?

时间:2014-11-19 18:29:08

标签: sql sql-server join greatest-n-per-group

在一个包含多个表格及其关系的数据库中,我想去年仅选择客户最近的付款。

我的查询是这样的:

SELECT
  P.Name,
  EV.EventName,
  FN.Installments,
  FN.PurchaseValue,
  FN.DueDate

FROM ClientPrivate PF
JOIN Client P        ON P.PesControle = PF.PesControle
JOIN ClientClass CP  ON P.PesControle = CP.PesControle
JOIN EVENT EV        ON CP.EveControle = EV.EveControle 
JOIN Class cc        ON cc.CurControle = EV.CurControle   
JOIN Finance FN      ON FN.PesControle = P.PesControle 

它返回我需要的值,只是我想只获得每个客户的最新购买,而不是所有客户。

我编辑以帮助澄清。 ' Controle'列是关键。

2 个答案:

答案 0 :(得分:2)

无论你的日期列是什么,都把它放在ROW_NUMBER()函数的ORDER BY子句中,你就可以了。

;WITH CTE AS
 (
 SELECT
  P.PesNome,
  EV.EveDescri,
  FN.FinTotParc,
  FN.FinVlrLiquido,
  FN.FinDiaVencto,
  ROW_NUMBER() OVER (PARTITION BY P.PesNome ORDER BY [DateColumn] DESC) rn

FROM PessoaFisica PF
JOIN Pessoa P        ON P.PesControle = PF.PesControle
JOIN CursoPessoa CP  ON P.PesControle = CP.PesControle
JOIN EVENTO EV       ON CP.EveControle = EV.EveControle 
JOIN Curso cc        ON cc.CurControle = EV.CurControle   
JOIN Financeiro FN   ON FN.PesControle = P.PesControle 
  )
SELECT * 
FROM CTE 
WHERE rn = 1

答案 1 :(得分:0)

我猜测Financeiro.FinDiaVencto是您的购买日期,而Pessoa.PesControle是一个人的唯一标识符。如果没有,您需要修改查询。我使用谷歌翻译葡萄牙语,但我还不清楚。

SELECT
  P.PesNome,
  EV.EveDescri,
  FN.FinTotParc,
  FN.FinVlrLiquido,
  FN.FinDiaVencto
FROM PessoaFisica PF
JOIN Pessoa P
  ON P.PesControle = PF.PesControle
JOIN CursoPessoa CP
  ON P.PesControle = CP.PesControle
JOIN EVENTO EV
  ON CP.EveControle = EV.EveControle 
JOIN Curso cc
  ON cc.CurControle = EV.CurControle   
JOIN Financeiro FN
  on FN.PesControle = P.PesControle 
WHERE EXISTS (
        SELECT 1
        FROM PessoaFisica PF_s
        JOIN Pessoa P_s
            ON P_s.PesControle = PF_s.PesControle
        JOIN CursoPessoa CP_s
            ON P_s.PesControle = CP_s.PesControle
        JOIN EVENTO EV_s
            ON CP_s.EveControle = EV_s.EveControle 
        JOIN Curso cc_s
            ON cc_s.CurControle = EV_s.CurControle   
        JOIN Financeiro FN_s
            on FN_s.PesControle = P_s.PesControle 
        WHERE P_s.PesControle = P.PesControle
        HAVING MAX(FN_s.FinDiaVencto) = FN.FinDiaVencto
    )

这应该返回每个Financeiro.FinDiaVencto最近Pessoa.PesControle的记录。如果您按需要或按事件(?)需要,您还需要修改WHERE子句以加入这些字段。

我不确定是否有必要加入PessoaFisica,但我加入了它,因为它可能会删除记录。您可以在子查询中包含GROUP BY,但 应该是多余的。