Tuesday, March 06, 2007

Correlated Subquerys

Ah, the wonderful Correlated Subquery...

This discovery neared completion with a google search for "t-sql select subquery parameter from select". Which returned a link to this article (http://www.databasejournal.com/features/mssql/article.php/3485291).

Why did I need subquery that made use of data from the outer query?

I've got a calendar table built using this article (http://sqlserver2000.databases.aspfaq.com/why-should-i-consider-using-an-auxiliary-calendar-table.html).
Now I have a need to return data from the Quarter Name column and the last date in that quarter for each line item. Sure there are lots of ways to do it, but a solution modified from the first referenced article allows me to do it in a single line of SQL.

I'd previously created a view (view_Quarters) to return DISTINCT quarter names (and id) for simplified inclusion in other queries.

Here's the Code:
SELECT
qn, qid, (SELECT TOP 1 dt FROM Calendar WHERE qid = vQ.qid ORDER BY dt DESC) LastDay
FROM
view_Quarters vQ ORDER BY qid

I knew what I wanted to happen ahead of time, but didn't know if it had been implemented SQL (ANSI or the flavor of my choice). It's always incredible to see that someone else had laid the groundwork for most of the problems you'll run into and even better with a good search engine to make that work easily available. Thank you DatabaseJournal, ASP.FAQ and Google.

Labels: ,

0 Comments:

Post a Comment

<< Home