views:

163

answers:

2

what I need to test for on my table is if there are rows for a given user id and order id on two separate days (DATETIME field for a timestamp).

I'm pretty sure I'd need a having clause and that's why I'm here...that frightens me terribly.

+1  A: 

Having shouldn't scare you, it is just a "Where" on an aggregated field:

Select UserID, Count(*) From OrderTbl Group By UserID Having Count(*) > 1

That'll give you all the Users that have multiple orders.

Select UserID, Count(*) From OrderTbl Where (UserID=@UserID) Group By UserID Having Count(*) > 1 

will give you the count if there are multiple records for the user id in @UserID and null if not.

if exists (Select UserID, Count(*) From OrderTbl Where (UserID=@UserID) Group By UserID 
             Having Count(*) > 1) Select 1 else Select 0

will return a 1 if there are multiple records for the User, 0 if not.

Update: Didn't realize that you could have multiple orders per day. This query will do what you want:

With DistinctDates as (Select Distinct UserID, [DATE] From OrderTbl Where (UserID=@UserID))
Select UserID, Count(*) From DistinctDates  
Group By UserID Having Count(*) > 1 
Mark Brittingham
this is a good start, but I need to test if they have orders placed on different days. IN other words, if they have 15 orders on 2/4/2010, it should still return a 0. If however they have 1 order on 2/3/2010, and 15 orders on 2/4/2010, it should return a 1.
Kyle
I tried grouping by my datestamp field thinking that would get me there, but no dice...any ideas?
Kyle
Fixed it, Kyle, once I came back and saw your note. Sorry for not reading more carefull the first time!
Mark Brittingham
great thank you very much!
Kyle
A: 

I am not sure if I understood your question, but this may work for you. The HAVING is your friend and you can still use the WHERE clause. This should let you know what order and user id combo is occuring more than once in the table.

SELECT [UserId], [OrderId]
FROM OrderTable 
WHERE UserId = @UserId
AND OrderId = @OrderId
GROUP BY UserId, OrderId
HAVING Count(*) > 1
AGoodDisplayName
and in addition, those records need to be on DIFFERENT days...
Kyle
I fixed the typo (my fault), but...the orginal question wasn't clear. It reads "if there are rows for a given [user id and order id] on two separate days". This query would give him a starting piont to then find those different days. There was no specifics given on the schema or the kind of data that would be populating the table. He didn't specify if he knew the OrderId or UserID he was looking for (sorry I made an assumption), or even if there could be multiple orders in a single day.
AGoodDisplayName
No apology necessary. I took off the downvote and will clear out the comments above. I hate downvoting people when they are just trying to be helpful so I'm happy to change the vote.
Mark Brittingham