SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 select items based on both before and after dates
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

mattt
Posting Yak Master

194 Posts

Posted - 05/16/2013 :  10:26:03  Show Profile  Reply with Quote
Hi,

Imagine a table like this:


    create table #productPurchases
    (	intRowId int identity(1,1),
		intItemId int,
		datPurchaseDate datetime
	)


It holds a record of items purchased and the date they were purchased. How would I write a query to identify items that had been purchased both before *and* after a certain date?

Tried this. Which didn't work, and bought back rather more records than I was expecting, mostly duplicates (the real table is a lot bigger) - but it illustrates what I'm trying to do.

SELECT TOP 1000 *
  FROM #productPurchases e1
  join #productPurchases e2
  on e1.strItemId = e2.strItemId
  where e1.datPurchaseDate> '2013-05-09 00:00:01'
  and e2.datPurchaseDate  < '2013-05-09 00:00:01'

MuMu88
Aged Yak Warrior

547 Posts

Posted - 05/16/2013 :  10:54:53  Show Profile  Reply with Quote
Try just this (without join and different dates in the date range):

SELECT TOP 1000 *
  FROM #productPurchases e1
  where e1.datPurchaseDate > '2013-05-10 00:00:01'
  and e1.datPurchaseDate  < '2013-05-09 00:00:01'


Go to Top of Page

mattt
Posting Yak Master

194 Posts

Posted - 05/16/2013 :  10:57:41  Show Profile  Reply with Quote
quote:
Originally posted by MuMu88

Try just this (without join and different dates in the date range):

SELECT TOP 1000 *
  FROM #productPurchases e1
  where e1.datPurchaseDate > '2013-05-10 00:00:01'
  and e1.datPurchaseDate  < '2013-05-09 00:00:01'




Thanks for the suggestion. But this returns nothing at all. And I'm certain there's data in that table which matches the requirement.
Go to Top of Page

MIK_2008
Flowing Fount of Yak Knowledge

Pakistan
1054 Posts

Posted - 05/16/2013 :  11:01:54  Show Profile  Reply with Quote
Change the AND with OR in your condition.

Another way would be to say
WHERE Date <> 'the date'

Cheers
MIK

Edited by - MIK_2008 on 05/16/2013 11:03:12
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.17 seconds. Powered By: Snitz Forums 2000