Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL select all records only if the sum is greater than 100

Tags:

sql

sum

I'm not exactly sure how to ask this so I'll give an example

I have a huge table that resembles something like this...

Name Widgets TransDate  Location
Abby  2      12/1/2010  Middleton
Abby  13     1/10/2011  Burmingham
Bobby 10     12/12/2011 Easton
Bobby 5      10/10/2011 Weston
.
.

And my current sql statement is...

SELECT name, widgets, TransDate, Location 
FROM MyTable
WHERE TransDate BETWEEN 1/1/2011 and 12/31/2011

to give me a table like this...

Name Widgets TransDate  Location
Abby  13     1/10/2011  Burmingham
Bobby 15     12/12/2011 Easton
Bobby 5      10/10/2011 Weston
.
.

How do I modify the above SQL to also get rid of the records of people who do not meet a Widget quota X... say X = 16. In this case, Abby would be dropped because her total # of widgets is 13 and Bobby's records would stay because his total is 20.

Thank you in advance!

like image 279
user1144191 Avatar asked Jan 11 '12 21:01

user1144191


1 Answers

If I understand your request, you want similar results to what you've already got, but filtering for those names who have met the quota. If that is correct, you can use an IN() subquery to find names grouped with >= 100 widgets.

SELET name, widgets, TransDate, Location FROM MyTable 
WHERE
  /* IN() subquery for names meeting the quota */
  name IN (
     SELECT name 
     FROM tbl 
     /* If they must have met the quota only during the time window, uncomment below */
     /* Otherwise, omit the WHERE clause to find those who have met the quota at any time */
     /* WHERE TransDate BETWEEN '1/1/2011' and '12/31/2011' */
     GROUP BY name 
     HAVING SUM(widgets) >= 100

  ) 
  AND TransDate BETWEEN '1/1/2011' and '12/31/2011'
like image 147
Michael Berkowski Avatar answered Sep 20 '22 09:09

Michael Berkowski