SUM一个分组字段

时间:2011-07-07 11:09:30

标签: mysql select group-by sum aggregate

我需要使用GROUP BYs对已经解决的列的内容进行求和。你究竟会怎么做?

该组应基于用户名,而不是结果集的全部内容。我认为这基本上是一个用户名字段的组,但我认为这将破坏查询当前的工作方式..

以下示例:

   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

1 个答案:

答案 0 :(得分: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