2017-08-11 49 views
0

此查詢中的所有內容除了第二個LEFT JOIN(其中BEGIN_DATE和END_DATE)都適用。因爲我必須按照附加列進行分組,所以它們可以用於「加入」,我得到了錯誤的數字。有沒有辦法做到這一點,而不必分組。我希望這是有道理的。基本上,因爲我必須將BEGIN_DATE和END_DATE包括在組中,所有內容都會丟失。聚合SQL查詢,GROUP BY引發問題

SELECT 
    to_char(T1.CALL_TIMESTAMP,'YYYY-IW') AS OMONTH 
    ,COUNT(T1.HOUSE) AS NODECALLS 
    ,T3.NODE_CODE 
    ,T5.NODECUSTCOUNT 
    ,T1.CALL_CATEGORY_LVL_3 
    ,sum((CASE WHEN T1.TC_WIP_TRANSACTION_ID IS NOT NULL THEN 1 ELSE 0 END)) AS TC 
    ,sum((CASE WHEN T1.TC_WIP_TRANSACTION_ID IS NOT NULL THEN 1 ELSE 0 END))/nullif(COUNT(T1.HOUSE), 0) AS SVRATEPERCALL 
    ,COUNT(T1.HOUSE)/ nullif(T5.NODECUSTCOUNT, 0) AS CALLRATE 

FROM CVKOMNZP.NZKOMUSER.NFOV_INBD_REMEDY_CALL_DETAILS T1 
LEFT JOIN 
     ( 
       SELECT T2.NODE_CODE,T2.BEGIN_DATE,T2.END_DATE,T2.HOUSE,T2.CORP 
       FROM CVKOMNZP.NZKOMUSER.D_HOUSEHOLD_CH_HIST T2 
     ) T3 
ON T1.CORP = T3.CORP AND T1.HOUSE = T3.HOUSE AND (T1.CALL_TIMESTAMP BETWEEN T3.BEGIN_DATE AND T3.END_DATE) 

LEFT JOIN 
     ( 
       SELECT count(ADM_HOUSEHOLD_ID) AS NODECUSTCOUNT,NODE_CODE,BEGIN_DATE, END_DATE 
       FROM CVKOMNZP.NZKOMUSER.D_HOUSEHOLD_CH_HIST 
       WHERE HOUSE_STATUS_CODE = 2 
        AND END_DATE = '2999-12-31 00:00:00' 
        AND T1.CALL_TIMESTAMP BETWEEN BEGIN_DATE AND END_DATE 
       GROUP BY NODE_CODE,BEGIN_DATE,END_DATE 

     ) T5 
ON T5.NODE_CODE = T3.NODE_CODE AND T1.CALL_TIMESTAMP BETWEEN T5.BEGIN_DATE AND T5.END_DATE 

WHERE T1.EXCLUSION_FLAG = 'N' 
     AND T1.CALL_TIMESTAMP >= To_Date ('07-29-2017', 'MM-DD-YYYY') AND T1.CALL_TIMESTAMP <= To_Date ('07-31-2017', 'MM-DD-YYYY') 

GROUP BY 
    to_char(T1.CALL_TIMESTAMP,'YYYY-IW') 
    ,T3.NODE_CODE 
    ,T5.NODECUSTCOUNT 
    ,T1.CALL_CATEGORY_LVL_3 
+0

我想你會需要顯示的樣本數據,目前的結果和預期的結果。 –

回答

0

如果我理解這個權利,您希望在沒有BEGIN和END DATE分組的情況下獲得COUNT。然而,因爲你的子查詢(第二個左連接)需要包含BEGIN和NEED,所以你不知道如何在沒有它的情況下進行分組。

如果是這種情況,您需要爲您的計數子查詢並將其連接回同一個表。

僅供參考:您的T1.CALL_TIMESTAMP在此子查詢中沒有意義,因爲您沒有稱爲T1的表。我將它重命名爲「a」。隨意將其改爲您想要的。

看看這有意義

LEFT JOIN 
    ( 
      SELECT a.BEGIN_DATE, 
        a.END_DATE, 
        node.NODECUSTCOUNT, 
        a.node_code 

      FROM CVKOMNZP.NZKOMUSER.D_HOUSEHOLD_CH_HIST a 

      /**Subquery to get a COUNT of all the Node based on NODE_CODE. 
       You link this back to your query above using the NODE CODE**/ 
      JOIN (SELECT count(ADM_HOUSEHOLD_ID) AS NODECUSTCOUNT, 
         NODE_CODE 
        FROM CVKOMNZP.NZKOMUSER.D_HOUSEHOLD_CH_HIST 
        GROUP BY NODE_CODE) node on node.node_code = a.node_code 

       WHERE a.HOUSE_STATUS_CODE = 2 
       AND a.END_DATE = '2999-12-31 00:00:00' 
       AND a.CALL_TIMESTAMP BETWEEN BEGIN_DATE AND END_DATE 

    ) ..JOIN THIS BACK TO YOUR MAIN TABLE  
+0

就是這樣,我得到稍微更高的數字,因爲子聯接,但我可以找出一個。感謝您的快速回復和答案。 –

+0

不客氣。很高興它解決了。 – Isaiah3015