为什么要使用相同的表别名并执行SELF JOIN

时间:2012-07-13 10:38:40

标签: sql sql-server sql-server-2008

我有一个sql script one tabletwo alias一起使用并在其上JOIN 但我需要了解为什么以及何时需要这样做 请详细说明?

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只有一张表,那么目的是做两个别名相同的表NAV [CURRENT]和NAV比较并使用LEFT JOIN?

请详细说明。

2 个答案:

答案 0 :(得分:4)

您正在比较表格中的2条记录

您需要两个不同的别名来表示两个不同的记录。

例如,如果您有一个名为Employees的表:(Id,Name,ManagerId),其中ManagerId是员工直接经理的Id

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

你想运行一个选择你的查询和你老板的名字:

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

答案 1 :(得分:1)

NAV正在加入自身,因此导航中每列实际上有两个实例。电流和比较用于区分它们。