SUM a grouped field
I need to SUM the contents of a column which is already worked out using GROUP BYs.. How exactly would you go about that?
The group should be based on the user name, not the entire contents of the result set. I believe this essentially a group by on that username field, but that i believe would break how the query currently works..
Example below:
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.ACC开发者_运维技巧TINPUTOCT, 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
Edit:
The columns would be: TOTAL_DOWNLOAD and TOTAL_UPLOAD
Thanks @ ypercube, worked a treat
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
精彩评论