Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 sub select

Author  Topic 

tjbarr
Starting Member

8 Posts

Posted - 2008-10-23 : 12:11:24
id giftdate
1 9/1/2008
1 9/1/2007
1 5/4/2004
2 8/6/2008
2 8/6/2007
3 4/3/2003
3 4/3/2002
4 4/3/2008
5 4/3/2007
I want a query with a sub selet to give me all id that gave more than 1 gift with at least one gift within 2007 or 2008.

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2008-10-23 : 12:38:33
SELECT ID
FROM MyTable
WHERE GiftDate > '20070101'
AND GiftDate < '20090101'
GROUP BY ID
HAVING COUNT(ID) > 0
Go to Top of Page

hanbingl
Aged Yak Warrior

652 Posts

Posted - 2008-10-23 : 12:41:16
FIXED:
quote:
Originally posted by Lamprey

SELECT ID
FROM MyTable
WHERE GiftDate >= '20070101'
AND GiftDate < '20090101'
GROUP BY ID
HAVING COUNT(ID) > 1

Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-10-23 : 12:46:08
or is it this?

SELECT ID
FROM MyTable
GROUP BY ID
HAVING COUNT(CASE WHEN GiftDate > '20070101'
AND GiftDate < '20090101' THEN ID ELSE NULL END) >= 1
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2008-10-24 : 03:12:10
quote:
Originally posted by visakh16

or is it this?

SELECT ID
FROM MyTable
GROUP BY ID
HAVING COUNT(CASE WHEN GiftDate > '20070101'
AND GiftDate < '20090101' THEN ID ELSE NULL END) >= 1



GiftDate > '20070101'
should be
GiftDate >= '20070101'


Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2008-10-24 : 03:41:09
Won't work.
What if one gift is made 2006 and one gift is made 2008?

SELECT		ID
FROM MyTable
GROUP BY ID
HAVING SUM(CASE WHEN GiftDate >= '20070101' AND GiftDate < '20090101' THEN 1 ELSE 0 END) > 0 -- Át least one gift during 2007 and 2008
AND COUNT(*) > 1 -- And at least two gifts in total, all according to OP spec



E 12°55'05.63"
N 56°04'39.26"
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-10-24 : 03:59:59
quote:
Originally posted by Peso

Won't work.
What if one gift is made 2006 and one gift is made 2008?

SELECT		ID
FROM MyTable
GROUP BY ID
HAVING SUM(CASE WHEN GiftDate >= '20070101' AND GiftDate < '20090101' THEN 1 ELSE 0 END) > 0 -- Át least one gift during 2007 and 2008
AND COUNT(*) > 1 -- And at least two gifts in total, all according to OP spec



E 12°55'05.63"
N 56°04'39.26"



yup thats right. I had missed that. thanks for spotting it
Go to Top of Page
   

- Advertisement -