MySQL 查询 - 分组依据问题
以下 MySQL 查询生成一个 session_ids 和相关用法的列表。我想做的是将每个会话分组为一行,并显示最大的上传和下载。用户名可以多次重复,必须在会话中进行分组。
当我尝试使用分组依据时,并不总是选择最好的。
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
The following MySQL query produces me a list of session_ids and associated usage. What i would like to do is group each session into one row with the greatest upload and download displaying. There can be multiple repeats of a user name, it has to be grouped on the session.
When I try and use group by, the greatest is not always selected.
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为此,您应该使用 MIN()/MAX() 聚合函数:
有关 MySQL 中聚合函数的更多信息:http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html
You should use MIN()/MAX() aggregate functions for this:
More about aggregate function in MySQL: http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html
注1:除了
IFNULL()
,您还可以使用COALESCE()
。它可能更可取,因为它可以有 2 个以上的参数,并且它也用于许多其他 RDBMS。:而不是
注释 2:您可以使用
:无需为表中的每一行调用 2 个函数。
Note 1: Instead of
IFNULL()
, you can also useCOALESCE()
. It may be preferable as it can have more than 2 arguments and it's also used in many other RDBMSs.Note 2: Instead of:
you can use:
No need to call 2 functions for every row in the table.