views:

235

answers:

4

Hi

In SQL Server 2008:

I have one table, and I want to do something along the following lines:

SELECT T1.stuff, T2.morestuff from
(
 SELECT code, date1, date2 from Table
) as T1
INNER JOIN
(
 SELECT code, date1, date2 from Table
) as T2

ON T1.code = T2.code and  T1.date1 = T2.date2

The two subqueries are exactly identical. Is there any way I can do this without repeating the subquery script?

Thanks

Karl

A: 

You can use a View.

CREATE VIEW myView AS 
SELECT code, date1, date2 
FROM Table

And then your query would be something like this:

SELECT T1.stuff, T2.morestuff 
FROM myView as T1
INNER JOIN myView as T2 ON T1.code = T2.code and  T1.date1 = T2.date2
Jhonny D. Cano -Leftware-
+6  A: 

CTE:

;WITH YourQuery AS
(
 SELECT code, date1, date2 from Table
)
SELECT 
    T1.stuff, T2.morestuff 
    from YourQuery           T1
        INNER JOIN YourQuery T2 ON T1.code = T2.code and  T1.date1 = T2.date2

FYI

In the question, the code is using derived tables, also known as inline views. A subquery is a SELECT query that returns a single value and is nested inside a SELECT, INSERT, UPDATE, or DELETE statement, or inside another subquery. A subquery can be used anywhere an expression is allowed. See: http://msdn.microsoft.com/en-us/library/aa213252(SQL.80).aspx

KM
Thanks. I am hoping that there is a performance gain to this - or does it only clean up the code? Is "YourQuery" only executed once, or does it redo the calculation every time you call SELECT ... from YourQuery?
Karl
I think it can reevaluate the CTE each time it is used, but this is the best way to be sure: In SQL Server Management Studio, run this command: `SET SHOWPLAN_ALL ON`, then run your original query. Your query will not run, but the execution plan will be displayed, look at the `TotalSubtreeCost` column for the first row containing "select". Run the CTE version of the query and again look at the `TotalSubtreeCost` column. Is there much difference? if not, then it is probably reevaluating it. You can look through the actual plan rows and see how SQL Server breaks your query into steps to work on.
KM
A: 

Why are they subqueries at all?

SELECT T1.stuff, T2.morestuff
FROM Table T1
INNER JOIN Table T2
ON T1.code = T2.code and T1.date1 = T2.date2
David Hedlund
`Why are they subqueries at all?` perhaps the OPs actual query is significantly more complex than the one listed in the question.
KM
A: 

Why wouldn't aliasing the table twice work?

SELECT T1.stuff, T2.stuff FROM Table as T1 INNER JOIN Table as T2
ON T1.code = T2.code and  T1.date1 = T2.date2
Mark