Given 2 tables, SAMPLE and SAMPLE_STATUS; SAMPLE is a generic pivoted table and SAMPLE_STATUS is an attribute-value format table looking like this:
From the SAMPLE_STATUS table, I only need to get the rows with the STATUS_ID = 2 and 4 to get the Login and Logout dates, respectively. Currently, I use 2 CTEs to get these values from the SAMPLE_STATUS table. Is there a better way to do this?
WITH CTE_StatusCreated AS (
SELECT ID, SAMPLE_ID, STATUS_DATE
FROM SAMPLE_STATUS
WHERE STATUS_ID = 2
),
CTE_StatusClosed AS (
SELECT ID, SAMPLE_ID, STATUS_DATE
FROM SAMPLE_STATUS
WHERE STATUS_ID = 4
)
SELECT
SAMPLE.ID
, CTE_StatusCreated.STATUS_DATE AS 'LOGIN_DATE'
, CTE_StatusClosed.STATUS_DATE AS 'LOGOUT_DATE'
FROM SAMPLE
LEFT JOIN CTE_StatusCreated
ON CTE_StatusCreated.SAMPLE_ID = SAMPLE.ID
LEFT JOIN CTE_StatusClosed
ON CTE_StatusClosed.SAMPLE_ID = SAMPLE.ID