Neo
Neo

Reputation: 16219

why to use same table alias and do SELF JOIN

I have one sql script in that one table is used with two alias and make a JOIN on it but I need to understand why and when it is needed to do so please elaborate ?

SELECT

             ISNULL(MarketValue,0)   
        FROM
            (                  
            SELECT TOP 5

                Delta,
                MarketValue     
            FROM
                (
                SELECT DISTINCT

                   FormatNumber(SUM([CURRENT].MarkToMarket), 0, ',', 0) AS Delta,
                    AVG([CURRENT].Mark) * SUM([CURRENT].Position) AS NumericPosition,
                    FormatNumber(AVG([CURRENT].Mark) * SUM([CURRENT].Position)* CASE WHEN [CURRENT].SecurityType IN ('Equity','Equity Option') THEN 100 ELSE 1 END, 0, ',', NULL)  AS MarketValue
                FROM
                    NAV [CURRENT]
                    LEFT JOIN
                    NAV Compare ON
                    [CURRENT].PurchaseLotId = Compare.PurchaseLotId AND
                    Compare.Date = '2012-06-06'
                WHERE

                    [CURRENT].SecurityType not in ('Equity')
                GROUP BY

                ORDER BY
                    NumericDelta DESC
            ) Movers
        FOR XML PATH ('TR'), TYPE
        ) AS VARCHAR(MAX)
    )

Why it is used like  FROM
                    NAV [CURRENT]
                    LEFT JOIN
                    NAV Compare ON
                    [CURRENT].PurchaseLotId = Compare.PurchaseLotId AND
                    Compare.Date = '2012-06-06'

NAV is only one table then what is the purpose to do take two alias of same table NAV [CURRENT] and NAV Compare and use LEFT JOIN?

please elaborate me.

Upvotes: 1

Views: 2721

Answers (2)

BonyT
BonyT

Reputation: 10940

You are comparing 2 records from the table

You need two different alias's to represent the two different records.

So for example if you had a table called Employees: (Id, Name, ManagerId) where ManagerId is the Id of an Employee's immediate manager

ID    Name     ManagerId
1      CEO        null
2     YourBoss      1
3      You          2

and you wanted to run a query that selected you and the name of your boss:

SELECT emp.Name, mgr.Name
FROM Employees emp INNER JOIN Employees mgr on emp.ManagerId = mgr.Id
WHERE emp.Id = 3

Upvotes: 4

AlexDev
AlexDev

Reputation: 4717

NAV is being joined with itself, so there are actually two instances of every column in nav. Current and compare are used to differentiate between them.

Upvotes: 1

Related Questions