根据列

时间:2016-10-28 10:03:52

标签: sql db2 dashdb

我无法理解这一个,我有一个好玩的"子查询:

SELECT  
"Requisition_ID",  
"Candidate_ID",  
"Application_Date",   
CA."Process_of_Activity",  
CA."Activity",   
"Completed_on",  
add_minutes(cast("Completed_on" as timestamp),STAT."Rank") as "Current Completed on"  

FROM CA

left join STATUS as STAT   
on CA."Process_of_Activity" = STAT."Process_of_Activity" and CA."Activity" = STAT."Activity"  
GROUP BY "Requisition_ID","Candidate_ID","Application_Date", STAT."Rank", CA."Process_of_Activity", CA."Activity", "Completed_on";  

这基本上给了我一个包含7列的表格。我需要一个结果与前3个相同的7列GROUPED,其中最后一列是Max。例如。如果原始子查询显示我:

Requisition_ID  Candidate_ID    Application_Date    Process_of_Activity Activity         Completed_on   Current Completed on
123              555            16/12/2015          To be Rejected      Rejection        08/03/2016     08/03/2016 00:29
123              555            16/12/2015          To be Rejected      Letter:Rejection 08/03/2016     08/03/2016 00:00
123              555            16/12/2015          Application Entry   Questionnaire    16/12/2015     16/12/2015 00:00
123              555            16/12/2015          Application Entry   Application Entr 08/03/2016     08/03/2016 00:01

在这种情况下,我只想查看此示例的第一行...所以我想分组 " Requisition_ID&#34 ;, " Candidate_ID&#34 ;, " Application_Date"

还要看看这些值是什么: CA" Process_of_Activity&#34 ;, CA"活动&#34 ;, " Completed_on"

"当前完成"是最大的   但当然还有更多的申请,候选人和申请日期。我正在使用dashDB。

1 个答案:

答案 0 :(得分:1)

您可以将row_number / rank / dense_rank用于此目的。您需要以下内容:

SELECT *
    FROM 
    (
    SELECT "Requisition_ID",
        "Candidate_ID",
        "Application_Date",
        "Process_of_Activity",
        "Completed_on",
        cco,
        ROW_NUMBER()OVER(PARTITION BY "Requisition_ID",
        "Candidate_ID",
        "Application_Date"
        ORDER BY cco DESC)rn
        FROM 
        (
        SELECT
            "Requisition_ID",
            "Candidate_ID",
            "Application_Date",
            CA."Process_of_Activity",
            CA."Activity",
            "Completed_on",
            add_minutes(CAST("Completed_on" AS TIMESTAMP),STAT."Rank") AS "cco"
            FROM CA
            LEFT JOIN STATUS AS STAT
            ON CA."Process_of_Activity" = STAT."Process_of_Activity" AND CA."Activity" = STAT."Activity"
            GROUP BY "Requisition_ID",
                "Candidate_ID",
                "Application_Date",
                STAT."Rank",
                CA."Process_of_Activity",
                CA."Activity",
                "Completed_on"
        ) AS INNER_QUERY)AS OUTER_QUERY
    WHERE rn=1    

此SQL不在dasdb上编译,但row_number函数很重要。它会给你一个想法。