SQL查询将行中的列放入一行

时间:2014-06-24 14:37:38

标签: sql database oracle

我有两张桌子:

  • 客户 (cust_id,cust_name)

  • 退款 (ref_id,cust_id,ref_date,ref_amount)

cust_id 是指向客户的外键。

每个客户可以有多次退款。我想获得一个客户列表,并且每个cutomer只有两个退款日期。每个客户和退款日期必须在一行。即我想得到愚蠢的结果:

(cust_name,ref_date1,ref_amount1,ref_date2,ref_amount2)

例如 - ' John Smith' 06/06 / 2012',500.0,' 08/05 / 2014',345.5

我怎么能得到这个? 感谢名单!

(如果重要的是我使用Oracle 11g)

1 个答案:

答案 0 :(得分:1)

以下内容获得最近两次退款:

select c.cust_name,
       max(case when seqnum = 1 then ref_date end) as ref_date1,
       max(case when seqnum = 1 then ref_amount end) as ref_amount1,
       max(case when seqnum = 2 then ref_date end) as ref_date2,
       max(case when seqnum = 2 then ref_amount end) as ref_amount2
from customer c join
     (select r.*,
             row_number() over (partition by cust_id order by ref_date desc) as seqnum 
      from refund r
     ) r
     on c.cust_id = r.cust_id
where seqnum <= 2
group by c.cust_name;