Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complicated mySQL Query Order By

Tags:

mysql

Example Data:

╔════╦════════════╦════════════╦═══════╦═══════════╦════════╗
║ ID ║   START    ║    STOP    ║ USER  ║   FILE    ║  SIZE  ║
╠════╬════════════╬════════════╬═══════╬═══════════╬════════╣
║  1 ║ 1330133409 ║ 1330133410 ║ user1 ║ file1.zip ║ 300000 ║
║  2 ║ 1330133409 ║ 1330133410 ║ user1 ║ file2.zip ║ 300500 ║
║  3 ║ 1330133409 ║ 1330133410 ║ user2 ║ file1.zip ║ 300000 ║
║  4 ║ 1330133409 ║ 1330133410 ║ user2 ║ file2.zip ║ 300500 ║
║  5 ║ 1330133409 ║ 1330133410 ║ user1 ║ file3.zip ║ 500000 ║
║  6 ║ 1330133409 ║ 1330133310 ║ user6 ║ file3.zip ║ 500000 ║
╚════╩════════════╩════════════╩═══════╩═══════════╩════════╝

I need to create a MySQL query that computes PER_USER_AVERAGE_BANDWIDTH where PER_USER_AVERAGE_BANDWIDTH = SUM(SIZE) / (STOP - START), and then order by PER_USER_AVERAGE_BANDWIDTH to produce results like this:

╔═══════╦════════════════════════════╗
║ USER  ║ PER_USER_AVERAGE_BANDWIDTH ║
╠═══════╬════════════════════════════╣
║ user3 ║ 110.37                     ║
║ user1 ║ 100.25                     ║
║ user2 ║ 75.70                      ║
╚═══════╩════════════════════════════╝

Clear as mud ;) Anyone?

like image 477
Daniel Abrams Avatar asked Dec 19 '12 22:12

Daniel Abrams


People also ask

Does ORDER BY make query faster?

To give an idea of how much slower only having the LIMIT clause is, with both, neither, or just ORDER BY, the queries take no more than about 10 seconds. With only the LIMIT clause however, the queries take about a minute 15, over 7 times as long!


2 Answers

I think your average should be total size over total duration, grouped by user:

SELECT   USER,
         SUM(SIZE) / SUM(STOP - START) AS PER_USER_AVERAGE_BANDWIDTH
FROM     my_table
GROUP BY USER
ORDER BY PER_USER_AVERAGE_BANDWIDTH DESC

See it on sqlfiddle.

like image 140
eggyal Avatar answered Sep 29 '22 08:09

eggyal


straight forward for average

SELECT 
  `user`,
  AVG( size / ( stop - start ) ) per_user_average_bandwidth
FROM
  tab_dl
GROUP BY `user`
ORDER BY per_user_average_bandwidth DESC

SQL Fiddle DEMO

like image 38
Sir Rufo Avatar answered Sep 29 '22 08:09

Sir Rufo