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!
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'
for sql server it could be done like this
SELECT m.name, m.widgets, m.TransDate, m.Location
FROM MyTable m
JOIN(SELECT name, SUM(widgets)
FROM MyTable
WHERE TransDate BETWEEN '1/1/2011' and '12/31/2011'
GROUP BY NAME
HAVING SUM(widgets) >= 16) x
ON x.NAME = m.NAME
WHERE m.TransDate BETWEEN '1/1/2011' and '12/31/2011'
For SQL Server 2005+ you could also try:
SELECT name, widgets, TransDate, Location
FROM (
SELECT name, widgets, TransDate, Location, SUM(widgets) OVER(PARTITION BY Name) Quant
FROM MyTable
WHERE TransDate BETWEEN 1/1/2011 and 12/31/2011) A
WHERE Quant >= 16
This is assuming that the quota must be meeted on the same date frame.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.