0

我已经有一个按天细分的视图(下面的查询中的 ByDay)。

现在我想过滤它,如果它的活动在前 10 个创收活动中,则结果中包含一行。

我得到了我想要的,但我有一种感觉,我可能会在此过程中跳过明显/正确的方法。

WITH T AS (
    SELECT
     ByDay.[Day]
    ,ByDay.[Campaign Name]
    ,ByDay.[Revenue USD]
    FROM ByDay
    WHERE ByDay.[Period]='Mar 2012'
),
TT AS (
    SELECT
     ByDay.[Campaign Name]
    ,SUM(ByDay.[Revenue USD]) [Sum Revenue USD]
    FROM ByDay
    WHERE ByDay.[Period]='Mar 2012'
    GROUP BY ByDay.[Campaign Name]
)
SELECT * FROM (
SELECT
     T.[Day]
    ,T.[Campaign Name]
    ,T.[Revenue USD]
    ,TT.[Sum Revenue USD]
    ,DENSE_RANK() OVER(ORDER BY TT.[Sum Revenue USD] DESC) AS R
    FROM T
    INNER JOIN TT ON T.[Campaign Name]=TT.[Campaign Name]
) TTT
WHERE R < 11
ORDER BY R

有没有更简单的方法来获得这样的东西?

4

1 回答 1

3

你可以SUM([Revenue USD])OVER(Partition By [Campaign Name])用来得到每个的总和Campaign Name。那么你只需要一个 CTE:

http://msdn.microsoft.com/en-us/library/ms189461.aspx

WITH T AS (
    SELECT
     ByDay.[Day]
    ,ByDay.[Campaign Name]
    ,ByDay.[Revenue USD]
    ,SUM(ByDay.[Revenue USD]) OVER(Partition By ByDay.[Campaign Name]) [Sum Revenue USD] 
    FROM ByDay
    WHERE ByDay.[Period]='Mar 2012'
)
SELECT * FROM (
SELECT
     T.[Day]
    ,T.[Campaign Name]
    ,T.[Revenue USD]
    ,T.[Sum Revenue USD]
    ,DENSE_RANK() OVER(ORDER BY T.[Sum Revenue USD] DESC) AS R
    FROM T
) TTT
WHERE R < 11
ORDER BY R
于 2012-04-18T20:57:13.753 回答