Sunday, February 12, 2012

Correlated Subquery, Common Table Expression example


Here are 3 different ways to write the same query.



The difference between using Self-Join method, CTE method, and Correlated Subquery method --> in Correlated Subquery method, I could use the ID column (which is the primary key column); but we cannot use ID in Group By (since it will be unique for each row), so we cannot use it in the Self-Join & CTE methods 
Hence, while writing Correlated Subqueries, we 'probably' have to focus on this --> returning the Primary Key of the outer query's table from the subquery
(This has to be verified by looking at examples)

From the table Challenge_Enter,
find out all the details of the latest Challenge to which the Customer 1123607 has entered into.

Self-Join
---------
SELECT
xx.*, Question1, Question2, Question3, Question4, Question5, Question6
FROM
Challenge_Enter yy
INNER JOIN
(SELECT
CustomerID, Challenge_Id, max(EnterDate) AS EnterDate
FROM
Challenge_Enter
WHERE
customerid = 1123607 AND Challenge_ID > 0
GROUP BY
Challenge_Id, CustomerID
) xx
ON yy.Challenge_ID = xx.Challenge_ID
WHERE
yy.EnterDate = xx.EnterDate

Common Table Expression
-----------------------
WITH
max_entries (Challenge_ID, maxEnterDate) As
(
SELECT
Challenge_id, max(EnterDate) maxEnterDate
from
Challenge_Enter
where CustomerID = 1123607 AND Challenge_ID > 0
group BY
Challenge_ID
)
SELECT
*
FROM
max_entries
INNER JOIN
Challenge_Enter
ON
max_entries.Challenge_ID = Challenge_Enter.Challenge_ID AND
max_entries.maxEnterDate = Challenge_Enter.EnterDate


Correlated Subquery
-------------------
SELECT
Challenge_ID,Question1,Question2,Question3,Question4,Question5,Question6
FROM
Challenge_Enter as CE1
WHERE
ID = (SELECT max(CE2.ID) From Challenge_Enter as CE2 WHERE CE2.CustomerID = 1123607 AND CE2.Challenge_ID = CE1.Challenge_ID AND Challenge_ID > 0 )

No comments:

Post a Comment

Followers

Blog Archive