x

Can I do a sub select statement in a view?

Is it possible to create sub select statements in a view?

I'm being asked to do something like this...

SELECT  Distinct    dbo.Table1.Co1, dbo.Table2.Co2, dbo.Table3.Co3, dbo.Table4.Co4, dbo.Table5.Co6,
                dbo.Table6.col4, Table7.col5

FROM              dbo.Table1 INNER JOIN
                  dbo.Table2 ON dbo.Table1.Col5 = dbo.Table2.Co5 LEFT OUTER JOIN
                  dbo.Table3 ON dbo.Table4.Co4 = dbo.Table5.Col1 ( Where Col1='Code')LEFT OUTER JOIN
dbo.Table6 ON dbo.Table2.Col7 = dbo.Table7.Col5 LEFT OUTER JOIN ... etc
more ▼

asked Jun 17 '11 at 03:15 PM in Default

technette gravatar image

technette
1.1k 76 91 101

(comments are locked)
10|1200 characters needed characters left

1 answer: sort voted first

you can either move that WHERE snippet to the end of the query as a regular where clause, which makes sense with the left table of a LEFT OUTER JOIN...

... WHERE dbo.Table5.Col1='Code'

or you can do it inline like you have it with an and

dbo.Table4.Co4 = dbo.Table5.Col1 AND Table5.Col1 = 'Code'

though I do have to wonder why you would LEFT OUTER JOIN Table3 with a test for equality between columns Table4 and Table5 (maybe Table5.Col1 is Table1.Col5?)
more ▼

answered Jun 17 '11 at 03:32 PM

KenJ gravatar image

KenJ
19.1k 1 3 11

+1, Nails it.
Jun 18 '11 at 02:56 AM Matt Whitfield ♦♦
+1 I think KenJ addresses this, but be clear that with outer joins, a condition in the WHERE clause is different than putting it in the JOIN and can return different row sets. With all inner joins this distinction goes away.
Jun 18 '11 at 09:20 AM Scot Hauder

Thanks Ken and Scot!

Also sorry to through you off with the LEFT OUTER JOIN...etc It was a quick rough example but I did get the answer on the correct syntax.
Jun 19 '11 at 11:15 PM technette
(comments are locked)
10|1200 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

New code box

There's a new way to format code on the site - the red speech bubble logo will automatically format T-SQL for you. The original code box is still there for XML, etc. More details here.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

SQL Server Central

Need long-form SQL discussion? SQLserverCentral.com is the place.

Topics:

x30

asked: Jun 17 '11 at 03:15 PM

Seen: 685 times

Last Updated: Jun 17 '11 at 03:26 PM