Oracle SQL嵌套分组

时间:2016-10-04 08:09:33

标签: sql oracle

输入

ID   Bet_Date              Event_name            Event_Class
1    20140828 10:31      Australia vs England    Cricket
1    20140829 08:31      Australia vs England    Cricket
1    20140829 12:31      West Indies vs England  Cricket
1    2014030 12:31       Kenya vs Ireland        Cricket

所需输出

ID   first_Prod_Bet_Date    First_Event_name         First_Event_Class Second_Prod_Bet_Date    Second_Event_name      Second_Event_Class   Third_Prod_Bet_Date    Third_Event_name  Third_Event_Class
1     20140828 10:31         Australia vs England       Cricket           20140829 12:31     West Indies vs England           Cricket       2014030 12:31          Kenya vs Ireland     Cricket

我的查询

SELECT cust_id,
     MIN (CASE WHEN ranking = 1 THEN event_name END) firstplayevent,
     MIN (CASE WHEN ranking = 1 THEN event_class END) firstEvent_Class,
     MIN (CASE WHEN ranking = 2 THEN event_name END) secondplayevent,
     MIN (CASE WHEN ranking = 2 THEN event_class END) secondplayClass,
     MIN (CASE WHEN ranking = 3 THEN event_name END) thirdplayevent,
     MIN (CASE WHEN ranking = 2 THEN event_class END) thirdplayClass
FROM (SELECT cust_id,
             event_name,
             event_class,
             bet_date,
             DENSE_RANK () OVER (PARTITION BY cust_id ORDER BY bet_date)
                AS ranking
        FROM FPeriod_Sports) a
WHERE a.ranking <= 3
    GROUP BY cust_id

查询结果

  ID      First_Event_name         First_Event_Class Second_Event_name Second_Event_Class   Third_Event_name  Third_Event_Class
  1     Australia vs England       Cricket      West Indies vs England  Cricket       Kenya vs Ireland     Cricket

2 个答案:

答案 0 :(得分:0)

    SELECT id,
min(case when ranking=1 then event_name  end )firstplayevent  ,min(case when ranking=1 then event_class  end )firstEvent_Class  ,min(case when ranking=1 then bet_date  end )firstplayeventdate ,
min(case when ranking=2 then event_name  end )secondplayevent ,min(case when ranking=2 then event_class  end ) secondplayClass   ,min(case when ranking=2 then bet_date  end )SecondPlayeventdate,
min(case when ranking=3 then event_name  end ) thirdplayevent ,min(case when ranking=2 then event_class  end ) thirdplayClass ,min(case when ranking=3 then bet_date  end )Thirdplayeventdate
FROM
            (SELECT 
                  cust_id,event_name,event_class,bet_date
                 ,dense_rank() OVER ( partition by cust_id ORDER BY bet_date ) as ranking 
             FROM Table_Name               ) a
WHERE  a.ranking <=3
group by id

答案 1 :(得分:0)

select *
from (
select cust_id,
             event_name,
             event_class,
             bet_date,
             DENSE_RANK () OVER (PARTITION BY cust_id ORDER BY bet_date) rnk
from t)
pivot (max(Bet_Date) as Bet_Date ,max(Event_name) as Event_name ,max(Event_Class) as Event_Class for rnk in (1 as "First",2 as "Second",3 as "Third",4 as "Forth"));