OUTER APPLY表自身多次 - 可以使用CASE

时间:2014-01-24 13:14:58

标签: sql-server tsql sql-server-2012

是否有必要在以下查询中多次OUTER APPLY,或者我可以通过某种方式使用1 APPLY和一些包含的CASE语句获得相同的结果?

(p.s。我意识到FIRST_VALUE是另一种选择,但我对使用APPLY

感兴趣
SELECT  
  Name,
  AgeCat,
  Country,
  X.DateKey,
  WagerAmt    = SUM(Revenue),
  FirstNAC    = z.DateKey,    
  FirstNA     = j.DateKey,
  FirstN      = q.DateKey  
FROM    #x X
    OUTER APPLY (
            SELECT  TOP(1) DateKey 
            FROM    #x Y
            WHERE   X.Name = Y.Name AND
                    X.AgeCat = Y.AgeCat AND
                    x.Country = y.Country 
            ORDER BY DateKey
            ) z
    OUTER APPLY (
            SELECT  TOP(1) DateKey 
            FROM    #x Y
            WHERE   X.Name = Y.Name AND
                    X.AgeCat = Y.AgeCat
            ORDER BY DateKey
            ) j
    OUTER APPLY (
            SELECT  TOP(1) DateKey 
            FROM    #x Y
            WHERE   X.Name = Y.Name
            ORDER BY DateKey
            ) q
GROUP BY  
    Name,
    AgeCat,
    Country,
    X.DateKey
    z.DateKey,    
    j.DateKey,
    q.DateKey;

1 个答案:

答案 0 :(得分:1)

我不知道如何用案例来做到这一点。某种类型的子选择是必要的。

编辑: 作为JOIN,查询将如下所示:

SELECT  
  Name,
  AgeCat,
  Country,
  X.DateKey,
  WagerAmt    = SUM(Revenue),
  FirstNAC    = z.DateKey,    
  FirstNA     = j.DateKey,
  FirstN      = q.DateKey  
FROM    #x X
inner join
(
    SELECT  TOP(1) DateKey 
    FROM    #x Y
    WHERE   X.Name = Y.Name AND
            X.AgeCat = Y.AgeCat AND
            x.Country = y.Country 
    ORDER BY DateKey
) z
inner join 
(
    SELECT  TOP(1) DateKey 
    FROM    #x Y
    WHERE   X.Name = Y.Name AND
            X.AgeCat = Y.AgeCat
    ORDER BY DateKey
) j
inner join (
    SELECT  TOP(1) DateKey 
    FROM    #x Y
    WHERE   X.Name = Y.Name
    ORDER BY DateKey
) q
GROUP BY  
    Name,
    AgeCat,
    Country,
    X.DateKey,
    z.DateKey,
    j.DateKey,
    q.DateKey;

请注意,GROUP BY也已更改:因为APPLY仅返回1行,理论上这些子选择可以返回多个,它们的字段也需要在GROUP中。