MySQL查询 - 按问题分组

时间:2011-07-07 09:04:52

标签: mysql sorting group-by sql-order-by

以下MySQL查询生成了session_ids列表和相关用法。我想做的是将每个会话分成一行,上传和下载显示最大。用户名可以有多个重复,必须在会话中分组。

当我尝试使用group by时,并不总是选择最大值。

  SELECT USERNAME, ACCTSESSIONID,
         IFNULL(ACCTINPUTGW ,0) * POW(2,32) + IFNULL(ACCTINPUTOCT , 0) as TOTAL_UPLOAD,
         IFNULL(ACCTOUTPUTGW,0) * POW(2,32) + IFNULL(ACCTOUTPUTOCT, 0) as TOTAL_DOWNLOAD
    FROM ACCOUNTING
   WHERE DATE_FORMAT(FROM_UNIXTIME(TIME_STAMP), '%Y-%m-%d') = '2011-07-05'
ORDER BY USERNAME ASC, ACCTSESSIONID 

-

USERNAME    ACCTSESSIONID        TOTAL_UPLOAD   TOTAL_DOWNLOAD
kor1        SESSION232442        341594114     5671726599
kor1        SESSION232442        331306202     5571382940
kor1        SESSION232444        338083784     5609510490
kor1        SESSION454355        323367019     5451121083
kor2        SESSION943209        323132957     5450522047  
ran32       SESSION934082        323132957     5450522047
ran62       SESSIONA34324        9532356       5450523537

2 个答案:

答案 0 :(得分:2)

你应该使用MIN()/ MAX()聚合函数:

SELECT USERNAME, ACCTSESSIONID,
     MAX(IFNULL(ACCTINPUTGW ,0) * POW(2,32) + IFNULL(ACCTINPUTOCT , 0)) as TOTAL_UPLOAD,
     MAX(IFNULL(ACCTOUTPUTGW,0) * POW(2,32) + IFNULL(ACCTOUTPUTOCT, 0)) as TOTAL_DOWNLOAD
FROM ACCOUNTING
WHERE
    DATE_FORMAT(FROM_UNIXTIME(TIME_STAMP), '%Y-%m-%d') = '2011-07-05'
GROUP BY
    USERNAME, ACCTSESSIONID
ORDER BY
    USERNAME ASC, ACCTSESSIONID 

有关MySQL中聚合函数的更多信息:http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html

答案 1 :(得分:1)

  SELECT USERNAME, ACCTSESSIONID,
         MAX(IFNULL(ACCTINPUTGW ,0) * POW(2,32) + IFNULL(ACCTINPUTOCT , 0))
           AS TOTAL_UPLOAD,
         MAX(IFNULL(ACCTOUTPUTGW,0) * POW(2,32) + IFNULL(ACCTOUTPUTOCT, 0))
           AS TOTAL_DOWNLOAD
    FROM ACCOUNTING
   WHERE DATE_FORMAT(FROM_UNIXTIME(TIME_STAMP), '%Y-%m-%d') = '2011-07-05'
GROUP BY USERNAME ASC, ACCTSESSIONID 
ORDER BY USERNAME ASC, ACCTSESSIONID 

注意1 :您也可以使用IFNULL()代替COALESCE()。它可能更好,因为它可以有两个以上的参数,它也可以在许多其他RDBMS中使用。

注2 :而不是:

DATE_FORMAT(FROM_UNIXTIME(TIME_STAMP), '%Y-%m-%d') = '2011-07-05'

你可以使用:

TIME_STAMP >= '2011-07-05'  AND  TIME_STAMP < '2011-07-06'

无需为表中的每一行调用2个函数。