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, 2011 at 03:15 PM in Default

technette gravatar image

technette
1.2k 87 102 109

(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, 2011 at 03:32 PM

KenJ gravatar image

KenJ
20.4k 1 4 12

+1, Nails it.
Jun 18, 2011 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, 2011 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, 2011 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.

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:

x33

asked: Jun 17, 2011 at 03:15 PM

Seen: 841 times

Last Updated: Jun 17, 2011 at 03:26 PM