Andrew Andrew - 1 month ago 5
SQL Question

How to nest select statements in SQL?

I'm trying to select only the

User_IDs
that are in the first select statement and the last select statement, but I am doing something wrong.

SELECT COUNT(DISTINCT User_ID) AS total
FROM UserClicks
WHERE (Date > :startDate AND Date < :endDate)
AND User_ID IN (
SELECT User_ID
FROM UserClicks
WHERE (Date > :monthBeforeStartDate AND Date < :startDate)
)


Update: This is for a MySQL database.

Answer

Sub-query and join will suit you here

SELECT DISTINCT u1.UserID 
FROM
  UserClicks u1
INNER JOIN
(
   SELECT 
      UserID 
   FROM 
     UserClicks 
   WHERE 
     (Date > :monthBeforeStartDate AND Date < :startDate)
) u2
ON u1.UserID = u2.UserID
WHERE
  (u1.Date > :startDate AND u1.Date < :endDate)