简体   繁体   中英

How can I create a view in SQL Server Management Studio using different where clause statements in it?

I have created some tables in the database, and I want to create a single view by picking columns from all those tables.

Here is my query:

CREATE VIEW dbo.View_Name
AS
    SELECT a.column1, a.column2, b.column1, b.column2, c.column1, c.column2
    FROM
        table1 AS a LEFT OUTER JOIN
        table2 AS b ON a.column1 = b.column1 LEFT OUTER JOIN
        table3 AS c ON b.column2 = c.column2
    WHERE   
    (a.[Load_Date] = (select max(Load_Date)
        From table1)

        and (b.[Load_Date] = (select max(Load_Date)
        From table2)

        and (c.[Load_Date] = (select max(Load_Date)
        From table3)

go

While I am trying to use multiple where clauses and complete the query, it is throwing me an error 'Incorrect Statement near 'go'.

I an new to SQL Server and I am stuck here. Can any one help me with completing my query with no errors?

your brackets in the WHERE are muddled - try this

CREATE VIEW dbo.View_Name

AS

SELECT a.column1, a.column2, b.column1, b.column2, c.column1, c.column2

FROM
table1 AS a LEFT OUTER JOIN

table2 AS b ON a.column1 = b.column1 LEFT OUTER JOIN

table3 AS c ON b.column2 = c.column2

WHERE
(a.[Load_Date] = (select max(Load_Date) From table1))

and (b.[Load_Date] = (select max(Load_Date) From table2))

and (c.[Load_Date] = (select max(Load_Date) From table3))

go

You could rewrite what you have as follows:

WITH T1 AS
    (SELECT TOP 1 WITH TIES
            Column1,
            Column2
     FROM Table1
     ORDER BY Load_Date DESC),
T2 AS
    (SELECT TOP 1 WITH TIES
            Column1,
            Column2
     FROM Table2
     ORDER BY Load_Date DESC),
T3 AS
    (SELECT TOP 1 WITH TIES
            Column1,
            Column2
     FROM Table3
     ORDER BY Load_Date DESC)
SELECT *
FROM T1
     JOIN T2 ON T1.Column1 = T2.Column1
     JOIN T3 ON T2.Column1 = T2.Column2;

Note I have used JOIN , as you reference the objects from the LEFT JOIN in the WHERE , making them implicit INNER JOIN s.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM