SQL查询,是否需要GROUP BY?如何避免不必要的复杂语法

时间:2016-09-19 08:19:21

标签: sql dashdb

我正在构建一个查询,它将基于4个表构建一个非常大的数据集。这是我到目前为止的查询:

SELECT  
CLIENT_CA."Requisition_ID",  
CLIENT_REQS."Requisition Title",  
CLIENT_REQS."Country",  
CLIENT_CD."Application_Status",  
CLIENT_CA."Candidate",  
CLIENT_CD."Gender",  
max(case when 
CLIENT_CA."Process_of_Activity" = 'Application Entry' then 
CLIENT_CA."Completed_on" end) as "ENTRY",  
max(case when 
CLIENT_CA."Process_of_Activity" = 'Candidate Selection' then 
CLIENT_CA."Completed_on" end) as "Selection",  
max(case when 
CLIENT_CA."Process_of_Activity" = 'Job Offer' then 
CLIENT_CA."Completed_on" end) as "Offer",  
CLIENT_RR."Status_Reason(E-Rec)"   
FROM CLIENT_CA  
LEFT JOIN CLIENT_CD ON (CLIENT_CA."Candidate_ID"=CLIENT_CD."Candidate_ID"
and CLIENT_CA."Requisition_ID"=CLIENT_CD."Requisition_ID" )  
LEFT JOIN CLIENT_REQS ON CLIENT_REQS."Requisition_ID"=CLIENT_CA."Requisition_ID"  
LEFT JOIN CLIENT_RR
ON (CLIENT_CA."Candidate_ID"=CLIENT_RR."Candidate_ID" and CLIENT_CA."Requisition_ID"=CLIENT_RR."Requisition_ID" )  
GROUP BY CLIENT_CA."Candidate"
   ,CLIENT_CA."Requisition_ID" 
  ,CLIENT_CD."Gender"
  ,CLIENT_REQS."Requisition Title"
  ,CLIENT_REQS."Country" 
  ,CLIENT_RR."Status_Reason(E-Rec)" 
  ,CLIENT_CD."Application_Status";

从技术上讲,这个查询工作得很好,并且正确地提供了我所需要的,没有错误。问题是我需要在SELECT子句和系统中添加大约80列,或者更确切地说逻辑强制我将我添加的每一列都放在GROUP BY子句中......我猜这&# 39;因为" max"功能。基本上CLIENT_CA是我的基础"表和我正在尝试实现MS Excel中的其他3个表上的VLOOKUP函数。我有点担心我会让这有点不必要地复杂化。请不要犹豫,告诉我,我只是简单的愚蠢:)但只有你有一个建议如何做得更好:)谢谢。哦......我在dashDB上运行它。

1 个答案:

答案 0 :(得分:1)

使用子查询从主表中提取,连接列和计算列(条目,选择,商品),以便您可以按列将组限制为固定数字

SELECT  
CA."Requisition_ID",  
REQS."Requisition Title",  
REQS."Country",  
CD."Application_Status",  
CA."Candidate",  
CD."Gender",  
"ENTRY",  
"Selection",  
"Offer",  
RR."Status_Reason(E-Rec)"   
FROM ( 
    SELECT 
        "Requisition_ID", "Candidate_ID", "Candidate",
        max(case when "Process_of_Activity" = 'Application Entry' then "Completed_on" end) as "ENTRY",  
        max(case when "Process_of_Activity" = 'Candidate Selection' then "Completed_on" end) as "Selection",  
        max(case when "Process_of_Activity" = 'Job Offer' then "Completed_on" end) as "Offer"
    FROM CLIENT_CA
    GROUP BY "Candidate", "Requisition_ID", "Candidate_ID" 
    ) AS CA 
LEFT JOIN CLIENT_CD AS CD ON (CA."Candidate_ID"=CD."Candidate_ID" and CA."Requisition_ID"=CD."Requisition_ID" )  
LEFT JOIN CLIENT_REQS AS REQS ON REQS."Requisition_ID"=CA."Requisition_ID" 
LEFT JOIN CLIENT_RR AS RR ON (CA."Candidate_ID"=RR."Candidate_ID" and CA."Requisition_ID"=RR."Requisition_ID" )