如何将此SQL翻译成更具可读性?

时间:2012-05-23 10:15:25

标签: sql sql-server

如何将其重写为“更简单”的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中的行的实例。

1 个答案:

答案 0 :(得分: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,但未加入第一个版本。