Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Sum with Sub Query?

Tags:

sql

Thanks for any help in advance, I can't wrap my SQL skills around this one... I have two tables like this:

Settings

Customerid     ViewerLimit
       1                   50
       2                   50

Distribution

Customerid     ServerIP
       1                 stream3
       1                 stream4
       2                 stream3

I want to calculate the load on each server. A customer divides the load if they have more than one server, so here customer 1 puts a load of 25 on each server. The result I'm trying to get is this:

ServerIP      Load
 stream3         75
 stream4         25

I tried to do a sum function similar to this:

sum(viewerlimit/(count # of servers)) as load group by serverip

But I can't do a sub query within a sum function. There are many customers and possibly many servers per customer so it will become too complex to do manually. I appreciate any input.

like image 898
gbusman Avatar asked Apr 03 '12 00:04

gbusman


1 Answers

Here is uninspired version with count in derived table:

select serverip, sum (viewerlimit/cast (ServerCount as float)) Load
from 
(
  select customerid, count(*) ServerCount from distribution group by customerid
) a
inner join settings
   on a.customerid = settings.customerid
inner join distribution 
   on settings.customerid = distribution.customerid
group by serverip

Sql Fiddle to play around

UPDATE - an attempt at explanation

Derived tables are used to produce ad-hoc result sets that can be joined to main body of a query. It is placed in from clause and enclosed in parenthesis. You can use anything an ordinary select can use, top, order by, aggregate functions etc. The only thing you cannot use is correlation to a table in main body. Oh, and CTE. Derived table must be aliased.

In previous sample derived table 'a' selects counts of servers by customerid. Main body sees it as a table with CustomerId and ServerCount columns, ready to be used as any column from all listed tables. A join on customerid is performed between settings and 'a'. As this is 1:1 relation (both tables produce single row given a customerid), no duplication occurs.

like image 59
Nikola Markovinović Avatar answered Oct 20 '22 20:10

Nikola Markovinović