0

您如何将其重写为“更简单”的 SQL:

SELECT tab1.ScenarioID, 
       tab1.TradeID, 
       tab1.Value AS Val1, 
       tab2.Value, 
       AS         Val2, 
       tab2.Value - tab1.Value 
FROM   (SELECT ScenarioID, 
               TradeID, 
               FileName, 
               Value, 
               Change 
        FROM   CalypsoResults 
        WHERE  FileName = 'x' 
               AND Date = '2012-05-17') tab1 
       LEFT JOIN (SELECT ScenarioID, 
                         TradeID, 
                         FileName, 
                         Value, 
                         Change 
                  FROM   CalypsoResults 
                  WHERE  FileName = 'x' 
                         AND Date = '2012-05-18') tab2 
         ON tab1.ScenarioID = tab2.ScenarioID 
            AND tab1.ID = tab2.ID 

我试过这个,但我没有得到相同的结果:

SELECT a.ScenarioID, 
       a.ID, 
       a.Date, 
       a.Value           AS Val1, 
       b.Value           AS Val2, 
       b.Value - a.Value AS Change 
FROM   CalypsoResults a 
       LEFT JOIN CalypsoResults b 
         ON a.ScenarioID = b.ScenarioID 
            AND a.ID = b.ID 
            AND a.FileName = B.FileName 
WHERE  a.Date = '2012-05-17' 
       AND ( b.Date = '2012-05-18' 
              OR b.Date IS NULL ) 
       AND a.FileName = 'x' 

第二个是错过了在a中有一行但在b中没有的实例。

4

1 回答 1

4

将表的第二个实例的所有JOIN谓词放入,而不是WHERE.

SELECT
    tab1.ScenarioID,
    tab1.TradeID,
    tab1.Value AS Val1,
    tab2.Value AS Val2,
    tab2.Value - tab1.Value
FROM CalypsoResults AS tab1
    LEFT JOIN CalypsoResults AS tab2 ON tab1.ScenarioID = tab2.ScenarioID
        AND tab2.FileName = 'x'
        AND tab2.Date = '2012-05-18'
        AND tab1.ID = tab2.ID
WHERE tab1.FileName = 'x'
    AND tab1.Date = '2012-05-17'

此外,您将加入FileName您的第二个版本,但不是第一个版本。

于 2012-05-23T10:23:00.967 回答