views:

27

answers:

3

I have a Users table and a Payments table. I need a query which lists the users who have a record in the payments table where PaymentStatus=1.

It must also only list users with a certain GroupID. The GroupID will be passed by a variable, but we can just call it 5 for simplicity.

The timestamp of the record (TimeCompleted) must also be less than a set timestamp, but we can just call this 10.

These are the columns in the tables (simplified):

     Users: UserID, GroupID, UserName
  Payments: PaymentID, UserID, PaymentStatus, TimeCompleted

The query should select the field UserName.

I did ask a similar question a few hours ago, but I asked it wrong and I couldn't get the queries to work properly for me. Also - if the user has more than one valid and active payment, it must only return the UserName once. When I tried to do it, I couldn't do this.

You can improve on my current query if you want to (it does everything apart from the last problem about duplicating the returned users). I might be going about it completely wrong though:

         SELECT `Users`.`UserName`
           FROM `Users`
LEFT OUTER JOIN `Payments` ON `Users`.`UserID` = `Payments`.`UserID`
          WHERE `Payments`.`TimeCompleted` < 10
            AND `Payments`.`PaymentStatus` = 1
            AND `Users`.`GroupID` = 5
A: 

the query would look like: SELECT * FROM Users U.GroupId = 5 WHERE U. U.UserId IN (SELECT P.UserID FROM PAYMENTS P WHERE P.PaymentCompleted = 1 AND P.TimeStamp <= @DateVar )

codewrath
A: 
select * 
from users uu
join payments p on p.userid=uu.userid
where p.paymentcompleted=1 and uu.groupId=5
Sparky
+1  A: 

You want to join across the two tables using the UserId key. The group by clause will limit to distinct username:

select UserName 
from Users inner join Payments on (Users.UserID = Payments.UserID)
where PaymentStatus = 1 and GroupID = 5 and TimeCompleted < 10 group by Users.UserID;
zevra0
Thank you so much! That worked perfectly :D
Matt