473,387 Members | 1,463 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Average on MAX by Group

Hi,

I have a database with 3 tables, Contacts, Hives, and Inspections with Contact ID as the key.

Contacts
ContactID | RunGroup

Hives
HiveID | ContactID

InspectionsNZ
ContactID | HiveID | Hive Strength | Date

Each contact has multiple hives and each hive has multiple inspections.

I am trying to average the hive strength from the latest of all inspections belonging to contacts in an individual group

So far i have

Expand|Select|Wrap|Line Numbers
  1. SELECT 
  2. ROUND(AVG(HiveStrength), 1) strength 
  3. FROM 
  4. InspectionsNZ
  5. LEFT JOIN Contacts ON Contacts.ContactID = InspectionsNZ.CustomerID 
  6. WHERE 
  7. Contacts.RunGroup = '$run'
  8. AND
  9. InspectionsNZ.Date IN (SELECT MAX(Date) FROM InspectionsNZ LEFT JOIN Contacts ON InspectionsNZ.CustomerID = Contacts.ContactID WHERE RunGroup = '$run' AND Contacts.Status = 'Active' AND Type = 'Rental')
  10. AND
  11. Contacts.Status = 'Active'
  12. AND 
  13. Type = 'Rental'
At the moment i am not getiing accurat averages, im not sure what it is averaging but its not giving the correct results.

Thanks for your help. Loving this forum.

Julian
Feb 2 '12 #1

✓ answered by Rabbit

Well, you can get rid of the subquery and do a join instead. Try this:
Expand|Select|Wrap|Line Numbers
  1. SELECT ROUND(AVG(HiveStrength), 1) strength
  2.  
  3. FROM InspectionsNZ
  4.    INNER JOIN (
  5.       SELECT Hive, MAX(`Date`) AS MaxDate
  6.       FROM InspectionsNZ
  7.          LEFT JOIN Contacts
  8.          ON InspectionsNZ.CustomerID = Contacts.ContactID
  9.       WHERE RunGroup = '$run'
  10.          AND Contacts.Status = 'Active'
  11.          AND Type = 'Rental'
  12.       GROUP BY Hive
  13.    ) t
  14.    ON InspectionsNZ.Hive = t.Hive
  15.       AND InspectionsNZ.`Date` = t.MaxDate
  16.  
  17.    LEFT JOIN Contacts
  18.    ON Contacts.ContactID = InspectionsNZ.CustomerID 
  19.  
  20. WHERE Contacts.RunGroup = '$run'
  21.    AND Contacts.Status = 'Active'
  22.    AND Type = 'Rental'

20 2757
Rabbit
12,516 Expert Mod 8TB
Can you post some sample data and results?
Feb 3 '12 #2
These are the Hive Strengths of the latest inspections from one group:

Hive Strenght | Date

0 2012/1/12
0 2012/1/12
8 2012/1/12
9 2012/1/12
5 2012/1/12
4 2012/1/12
1 2012/1/12
0 2012/1/12
8 2012/1/12
6 2012/1/12
0 2012/1/12
0 2012/1/12
7 2012/1/12
2 2012/1/12


This should average 3.5 but it is giving me and average of 0


Group Hives|Customers|Avg Hive Strength
Waitakere 14 7 0
Mt Albert 18 9 5
Ponsonby 18 9 0
Manukau 20 10 8
North Shore 26 13 1.5
Remuera 29 15 3
Titirangi 29 15 3
Kumeu 30 13 5.458
Mt Eden 31 16 5.714


This is the table i am outputting the data too
Feb 3 '12 #3
Rabbit
12,516 Expert Mod 8TB
Have you tried the select statement without the aggregation to see what records it returns? To make sure it's returning the correct records to average on??
Feb 3 '12 #4
you mean take out the MAX from the sub query?

Also, would it matter if "hiveStrength' was 0 ?
Feb 3 '12 #5
Ok, have taken out the AVG (i get what you meant now) and for the example i gave it is averaging 0 0 instead of


0 2012/1/12
0 2012/1/12
8 2012/1/12
9 2012/1/12
5 2012/1/12
4 2012/1/12
1 2012/1/12
0 2012/1/12
8 2012/1/12
6 2012/1/12
0 2012/1/12
0 2012/1/12
7 2012/1/12
2 2012/1/12
Feb 3 '12 #6
Ok i think i know what the problem might be.... the sub query is looking for the MAX date so it will average only the HiveStrengths of inspections done on the latest date for each group.

Instead it should be averaging the hive strength of the latest inspection for each hive in the group... if that makes any sense?
Feb 3 '12 #7
Rabbit
12,516 Expert Mod 8TB
So when you took out the average, it was returning the correct records? Or is it returning the wrong records?
Feb 3 '12 #8
wrong,

should be 0 0 8 9 5 4 1 0 8 6 0 0 7 2

what is getting is 0 0
Feb 3 '12 #9
Rabbit
12,516 Expert Mod 8TB
Oh, I see what it is now. In your Max(Date), use Max([Date]) instead. Date is a reserved function, you should try not to use it as a column name. So to bypass it, you need to demarcate it as a field.
Feb 3 '12 #10
Invalid query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[Date]) FROM InspectionsNZ LEFT JOIN Contacts ON InspectionsNZ.CustomerID = Con' at line 9
Feb 3 '12 #11
Rabbit
12,516 Expert Mod 8TB
Oh mySQL, I believe they use ` ` to demarcate a field.
Feb 3 '12 #12
nope still get the 0 0 with 'Date' and `Date` good thinking though...

Thanks for your help...
Feb 3 '12 #13
Rabbit
12,516 Expert Mod 8TB
Run just the subquery and see if it returns the correct date. And use `Date`
Feb 3 '12 #14
I am getting only one date for each group where i should be getting all MAX inspection Dates for each hive in the group.



Expand|Select|Wrap|Line Numbers
  1. SELECT MAX(`Date`) strength FROM InspectionsNZ LEFT JOIN Contacts ON InspectionsNZ.CustomerID = Contacts.ContactID WHERE RunGroup = '$run'
Group Hives Customers Avg Hive Strength
Kumeu 30 13 19-12-11
Manukau 20 10 20-12-11
Mt Albert 18 9 19-01-12
Mt Eden 31 16 19-01-12
North Shore 26 13 22-01-12
Ponsonby 18 9 12-01-12
Remuera 29 15 22-01-12
Titirangi 29 15 22-01-12
Waitakere 14 7 12-01-12
Feb 3 '12 #15
Rabbit
12,516 Expert Mod 8TB
Well, it's not going to give you max `date` by `hive` because you didn't specify which `hive` in the query.
Feb 3 '12 #16
makes sense...

would that be best done using another sub query or is there another more efficient way way to join 3 tables ?
Feb 3 '12 #17
if i do:
Expand|Select|Wrap|Line Numbers
  1. SELECT MAX(`Date`) strength FROM InspectionsNZ WHERE HiveID IN(SELECT Hives.ID FROM Hives LEFT JOIN Contacts ON Contacts.ContactID = Hives.ContactID WHERE RunGroup = '$run' GROUP BY Hives.ID)
i get single dates

but when i just run the sub query i do get all the hiveID's
Expand|Select|Wrap|Line Numbers
  1. SELECT Hives.ID strength FROM Hives LEFT JOIN Contacts ON Contacts.ContactID = Hives.ContactID WHERE RunGroup = '$run' GROUP BY Hives.ID

how would the query be structured ?
Feb 3 '12 #18
Rabbit
12,516 Expert Mod 8TB
Well, you can get rid of the subquery and do a join instead. Try this:
Expand|Select|Wrap|Line Numbers
  1. SELECT ROUND(AVG(HiveStrength), 1) strength
  2.  
  3. FROM InspectionsNZ
  4.    INNER JOIN (
  5.       SELECT Hive, MAX(`Date`) AS MaxDate
  6.       FROM InspectionsNZ
  7.          LEFT JOIN Contacts
  8.          ON InspectionsNZ.CustomerID = Contacts.ContactID
  9.       WHERE RunGroup = '$run'
  10.          AND Contacts.Status = 'Active'
  11.          AND Type = 'Rental'
  12.       GROUP BY Hive
  13.    ) t
  14.    ON InspectionsNZ.Hive = t.Hive
  15.       AND InspectionsNZ.`Date` = t.MaxDate
  16.  
  17.    LEFT JOIN Contacts
  18.    ON Contacts.ContactID = InspectionsNZ.CustomerID 
  19.  
  20. WHERE Contacts.RunGroup = '$run'
  21.    AND Contacts.Status = 'Active'
  22.    AND Type = 'Rental'
Feb 4 '12 #19
worked a treat, will take me a while to work out whats happening with that one but thank you so much for your help.

You are a legend!
Feb 4 '12 #20
Rabbit
12,516 Expert Mod 8TB
Not a problem. Good luck.

Basically the inner join returns all the hives and their max date and joins it to the main table to filter down to just those records.
Feb 4 '12 #21

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: Stephen Miller | last post by:
Hi, I am trying to add a staggered running total and average to a query returning quarterly CPI data. I need to add 4 quarterly data points together to calculate a moving 12-month sum (YrCPI),...
6
by: Stephen Miller | last post by:
Firstly, sorry for the long post, but I've included a fair bit of sample data. Im doing a comparision of 10yr Bond prices and CPI adjustments, with an 18 week moving average of the CPI. I'm...
5
by: Mike Bannon | last post by:
Hi All We have an order processing database which includes the standard Order Header/Order Lines tables. I'm trying to write a query to get the average number of lines per order over a given...
9
by: cyrus.kapadia | last post by:
Let's say I have the following table: entry product quality 1 A 80 2 A 70 3 A 80 4 B 60 5 B 90 6 ...
2
by: Karen | last post by:
I inserted this statement and it worked great for the customers that have no payment history, but for the customers that have a history and an open invoice, it still used today's date in the mix...
10
by: Rudolf Bargholz | last post by:
Perhaps some kind soul could help me out with an SQL I have been trying all day to get to work, where one colum is just not summing up the way I want it to. I have the following data GRP_SEQ ...
3
by: mochatrpl | last post by:
I am looking for a way to make a query / report display the running average for total dollars. I have already set up a query to provide totals dollars per day from which a report graphly shows...
0
by: dragon52 | last post by:
Hi there, I have records in the form of scorecards. Each scorecard has fields "type" and "score". eg typeA 2.3 typeB 3.3 typeA 2.0 typeC 1.9 typeB 1.1
1
by: indosmoke | last post by:
Hey all, I'm trying to get a total average of the daily average. Below is my query for getting the daily average: SELECT DailyAverage=AVG(T.Photo_Reading) ,date=s.H_date FROM T...
3
by: izharmel | last post by:
Hi, I have a function in Access VBA which uses an SQL code to create an average table from an existing table. The original table may look something like this: Time ...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.