如何仅显示每个帐户的第二次购买

时间:2017-01-27 12:22:15

标签: mysql

我有一个交易表,其中显示了多个账户进行的各种交易。有些只做一个,有些做得多。目前SQL我打印出第一次购买每个帐户但我需要它打印出每个帐户制作的第二个

SELECT account_id
     , purchase_date as second_purchase
     , amount as second_purchase_amount
FROM Transactions t
WHERE purchase_date NOT IN (SELECT MIN(purchase_date)
                            FROM Transactions m
                            )
GROUP BY account_id
HAVING purchase_date = MIN(purchase_date);

选择第二个购买日期和金额需要更改什么?我尝试为account_id添加一个计数,但它给了我错误的值。

2 个答案:

答案 0 :(得分:1)

您可以使用变量来分配行号并获得第二次购买。

SELECT account_id,purchase_Date,amount 
FROM (
     SELECT account_id
         ,purchase_date
         ,amount
         --, @rn:=IF(account_id=@a_id and @pdate <> purchase_date,@rn+1,1) as rnum
         ,case when account_id=@a_id and @pdate <> purchase_date then @rn:=@rn+1
               when account_id=@a_id and @pdate=purchase_date then @rn:=@rn
          else @rn:=1 end as rnum
         , @pdate:=purchase_date
         , @a_id:=account_id
     FROM Transactions t
     CROSS JOIN (SELECT @rn:=0,@a_id:=-1,@pdate:='') r
     ORDER BY account_id, purchase_date
    ) x 
WHERE rnum=2

解释它的工作原理:

  • @rn:=0,@a_id:=-1,@pdate:='' - 声明3个变量并初始化它们,@ rn用于分配行号,@ a_id用于保存account_id,@ update用于保存purchase_date。

  • 对于第一行(按account_id和purchase_date排序),将比较account_id和@a_id,@ update和purchase_date。由于它们不相等,when条件失败,else部分将分配@ rn = 1。此外,变量赋值发生在此之后。 @aid和@pdate将更新为当前行的值。对于第二行,如果它们是同一个帐户,并且在不同的日期,将执行第一个when条件,并且@rn将增加1.如果存在关联,则第二个when条件将执行并且@rn保持不变。您可以运行内部查询来检查变量的分配方式。

答案 1 :(得分:0)

对行进行编号,然后选择RowNumber = 2

select *
from (
    select
         @rn := case when @account_id = account_id then @rn + 1 else @rn := 1 end as RowNumber,
         @account_id := account_id as account_id, 
         purchase_date
    from 
        (select @rn := 1) x,
        (select @acount_id :=account_id as account_id, purchase_date 
         from Transactions 
         order by account_id, purchase_date)  y
     ) z
where RowNumber = 2;