如何将数据模式组成1行

时间:2017-08-26 07:07:22

标签: sql oracle listagg

我需要将表记录写入平面文件。 这是要求: 我必须找到过滤列相同的所有列,在这种情况下,行将写在平面文件的同一行,列名为前缀到值。这里col1和col2将形成一个独特的记录。

输入表:

;WITH SUM_View_Stats AS 
(
    SELECT 
        challenge_id,
        total_views = SUM(total_views),
        total_unique_views = SUM(total_unique_views)
    FROM 
        View_Stats 
    GROUP BY 
        challenge_id
)
, SUM_Submission_Stats AS  
(
    SELECT 
        challenge_id,
        total_submissions = SUM(total_submissions),
        total_accepted_submissions = SUM(total_accepted_submission)
    FROM 
        Submission_Stats 
    GROUP BY 
        challenge_id
)
SELECT  
    con.contest_id, con.hacker_id, con.name,
    SUM(total_submissions),
    SUM(total_accepted_submissions),
    SUM(total_views),
    SUM(total_unique_views)
FROM 
    Contests con
INNER JOIN 
    Colleges col ON con.contest_id = col.contest_id
INNER JOIN 
    Challenges cha ON cha.college_id = col.college_id
LEFT JOIN 
    SUM_View_Stats vs ON vs.challenge_id = cha.challenge_id
LEFT JOIN 
    SUM_Submission_Stats ss ON ss.challenge_id = cha.challenge_id
GROUP BY 
    con.contest_id, con.hacker_id, con.name
HAVING 
    (SUM(total_submissions) +
     SUM(total_accepted_submissions) +
     SUM(total_views) + 
     SUM(total_unique_views)) <> 0
ORDER BY
    con.contest_ID

输出:

col1 col2 col3 col4  
A    B     1    HELLO  
C    X     5    DEMO  
A    B     2    TEXT  

1 个答案:

答案 0 :(得分:0)

这是一个与发布的样本数据和输出一起使用的解决方案。它分两步工作:连接每一行的列,然后使用LISTAGG()聚合col1, col2组合的所有行。

SQL> with cte as (
  2     select col1
  3            , col2
  4            , 'col3:' || col3 ||' col4:' || col4 as col3col4
  5            , row_number() over (partition by col1, col2 order by col1, col2) as rn
  6     from input_table
  7  )
  8  select col1
  9         , col2
 10         , listagg(col3col4, ' ') within group (order by rn) as concat_output
 11  from cte
 12  group by col1, col2;

COL1 COL2 CONCAT_OUTPUT
---- ---- ----------------------------------------
A    B    col3:2 col4:TEXT col3:1 col4:HELLO
C    X    col3:5 col4:DEMO
SQL>