2011-07-07 97 views
0

我需要SUM使用GROUP BYs已經計算出的列的內容。您究竟會如何去做呢?SUM分組字段

該組應該基於用戶名,而不是結果集的全部內容。我認爲這基本上是一組由該用戶名的領域,但我相信會打破目前的查詢如何運作..下面

例子:

SELECT A1.USERNAME, DATE_FORMAT(FROM_UNIXTIME(A1.TIME_STAMP),'%Y-%m-%d') AS DTTM, A1.ACCTSESSIONID, 
      MAX(IFNULL(A1.ACCTINPUTGW,0) * POW(2,32) + IFNULL(A1.ACCTINPUTOCT, 0)) - MAX(IFNULL(A2.ACCTINPUTGW,0) * POW(2,32) + IFNULL(A2.ACCTINPUTOCT, 0)) as TOTAL_UPLOAD, 
      MAX(IFNULL(A1.ACCTOUTPUTGW,0) * POW(2,32) + IFNULL(A1.ACCTOUTPUTOCT, 0)) - MAX(IFNULL(A2.ACCTOUTPUTGW,0) * POW(2,32) + IFNULL(A2.ACCTOUTPUTOCT, 0)) as TOTAL_DOWNLOAD 

    FROM ACCOUNTING A1 

LEFT JOIN ACCOUNTING A2 
     ON A1.ACCTSESSIONID = A2.ACCTSESSIONID 
     AND DATE_FORMAT(FROM_UNIXTIME(A2.TIME_STAMP), '%Y-%m-%d') = '2011-07-04' 

    WHERE DATE_FORMAT(FROM_UNIXTIME(A1.TIME_STAMP), '%Y-%m-%d') = '2011-07-05' 
GROUP BY A1.ACCTSESSIONID,A2.ACCTSESSIONID 
ORDER BY A1.USERNAME 

編輯:

列是: TOTAL_DOWNLOAD和TOTAL_UPLOAD

+0

Tr的y刪除所有與您的問題無關的代碼,並僅發佈剩餘的內容 – Bohemian

+1

讓此查詢被稱爲'Q'。把它放在另一個像這樣的內容中:'SELECT FROM FROM(Q)AS q GROUP BY USERNAME' –

回答

1

感謝@ ypercube,工作一種享受

SELECT A3.USERNAME 
    , SUM(A3.TOTAL_UPLOAD) AS FINAL_UPLOAD 
    , SUM(A3.TOTAL_DOWNLOAD) AS FINAL_DOWNLOAD 
FROM 
    (SELECT 
     A1.USERNAME 
     , DATE_FORMAT(FROM_UNIXTIME(A1.TIME_STAMP),'%Y-%m-%d') AS DTTM 
     , A1.ACCTSESSIONID 
     , MAX(IFNULL(A1.ACCTINPUTGW,0) * POW(2,32) + IFNULL(A1.ACCTINPUTOCT, 0)) 
     - MAX(IFNULL(A2.ACCTINPUTGW,0) * POW(2,32) + IFNULL(A2.ACCTINPUTOCT, 0)) 
     AS TOTAL_UPLOAD 
     , MAX(IFNULL(A1.ACCTOUTPUTGW,0) * POW(2,32) + IFNULL(A1.ACCTOUTPUTOCT, 0)) 
     - MAX(IFNULL(A2.ACCTOUTPUTGW,0) * POW(2,32) + IFNULL(A2.ACCTOUTPUTOCT, 0)) 
     AS TOTAL_DOWNLOAD    
    FROM ACCOUNTING A1 
     LEFT JOIN ACCOUNTING A2 
     ON A1.ACCTSESSIONID = A2.ACCTSESSIONID 
     AND DATE_FORMAT(FROM_UNIXTIME(A2.TIME_STAMP), '%Y-%m-%d') = '2011-07-04' 
    WHERE DATE_FORMAT(FROM_UNIXTIME(A1.TIME_STAMP), '%Y-%m-%d') = '2011-07-05' 
    GROUP BY A1.ACCTSESSIONID,A2.ACCTSESSIONID 
    ORDER BY A1.USERNAME 
) AS A3  
GROUP BY A3.USERNAME 
+0

你不需要子查詢中的ORDER BY。如果您需要訂購,請將其置於外部查詢。 –

+0

啊,我看到了,好點..再次感謝:) – Lee