I have some tables:
SessionID int PK
Created datetime
SiteId int FK
ParamID int PK
ParamName nvarchar
SessionID int FK
ParamID int FK
ParamValue nvarchar
SiteID int FK
ParamID int FK
ParamKey nvarchar
Sessions : Contains the unique session id for a visitor and the time they entered the site.
Tracking_Parameters : Contains a list of things that you may want to track on a site (ie Email Open, Email Click, Article Viewed, etc.)
Site_Custom_Parameters : For a particular site (table not shown), declares the key value for a Tracking_Parameter (ie the key to look for in a query string or route)
Session_Custom_Tracking : The link between a session and a tracking parameter and also contains the value for the parameter's key when it was found by my application.
Question:
I want to select session id's where for these particular sessions, there is a record in the Session_Custom_Tracking for two different ParamID's. I want to find sessions where a user both opened an email (paramid 1) and clicked (paramid 3) a link in that email.
You can join to the same table twice:
SELECT S.SessionID
FROM Sessions AS S
JOIN Session_Custom_Tracking AS SCT1
ON SCT1.SessionID = S.SessionID
AND SCT1.ParamID = 1
JOIN Session_Custom_Tracking AS SCT2
ON SCT2.SessionID = S.SessionID
AND SCT2.ParamID = 3
An alteranative that might be easier to read (because it more closely matches the way you describe the problem) is to use WHERE EXISTS
:
SELECT S.SessionID
FROM Sessions AS S
WHERE EXISTS
(
SELECT *
FROM Session_Custom_Tracking AS SCT1
WHERE SCT1.SessionID = S.SessionID
AND SCT1.ParamID = 1
)
AND EXISTS
(
SELECT *
FROM Session_Custom_Tracking AS SCT2
WHERE SCT2.SessionID = S.SessionID
AND SCT2.ParamID = 3
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.