SS_11
SS_11

Reputation: 49

select a row based on a particular condition

I have a table like this:

CustID     VisitTime
 1         2012-12-31 11:59
 1         2013-1-1 00:00
 1         2013-1-1 00:05
 2         2013-1-1 00:20
 2         2013-1-1 10:00
 3         2013-1-1 11:40

Now, I want to choose those new customers whose visited the site from Jan 1st 12:00AM to Jan 31st 11:59pm.

For example: cust ID 1 also visited in Dec, hence cust ID 1 should not be selected. Only 2 and 3 should be selected.

How do I incorporate this logic using t-sql?

Upvotes: 2

Views: 127

Answers (2)

valex
valex

Reputation: 24134

SELECT DISTINCT CUSTID
FROM T as T1
WHERE VisitTime between '2013-01-01 00:00' AND '2013-01-31 23:59'
AND NOT EXISTS (SELECT T.CustID FROM T 
                       WHERE T.CustId=T1.CustId and VisitTime < '2013-01-01')

Upvotes: 0

Rapha&#235;l Althaus
Rapha&#235;l Althaus

Reputation: 60493

SELECt t.CustID
FROM Table1 t
GROUP BY t.CustID
HAVING MIN(VisitTime) >='01/01/2013 00:00:00' AND MIN(VisitTime) < '02/01/2013 00:00:00'
--same test on MAX(vistTime) if needed

SqlFiddle

Upvotes: 5

Related Questions