ROW_NUMBER()OVER(PARTITION BY)显示Group By Clause的重复结果

时间:2014-10-22 16:16:13

标签: sql sql-server ssrs-2008 where-clause

我创建了以下查询来显示一年的“最后”值的总和,通常这是十二月的值,但是这一年可能会在任何一个月结束,所以我想将最后的值加在一起为每个goalmontecarloheaderid。我有99%的工作,但[年]值有一些随机重复。

WITH endBalances AS (
        SELECT ROW_NUMBER() OVER (PARTITION By GoalMonteCarloHeaderID, Year(Convert(date,MonthDate)) Order By Max(Month(Convert(date,MonthDate))) desc) n, Max(Month(Convert(date,MonthDate))) maxMonth, GrowthBucket, WithdrawalBucket, NoTaxesBucket,
        Year(MonthDate) [year]
        From GoalMonteCarloMedianResults mcmr
        full join GoalMonteCarloHeader mch on mch.ID = mcmr.GoalMonteCarloHeaderID
        full join GoalChartData gcd on gcd.ID = mch.GoalChartDataID and gcd.TypeID = 2
        inner join Goal g on g.iGoalID = gcd.GoalID
        where g.iTypeID in (1) and g.iHHID = 850802
        group by GoalMonteCarloHeaderID, MonthDate, GrowthBucket, WithdrawalBucket, NoTaxesBucket
)
SELECT [year], Sum(GrowthBucket) GrowthBucket, Sum(WithdrawalBucket) WithdrawalBucket,Sum(NoTaxesBucket) NoTaxesBucket, maxMonth
From endBalances 
where [year] is not null and n=1
Group By [year], maxMonth
order by [year] asc

在数据库结果中显示两个随机重复项; enter image description here

你可以在图片中看到有两个例子,其中年份重复并显示的不仅仅是一年中的“最后一个月”。我是否在我的查询中使用了组或者PARTITION BY()做错了什么?我不是最熟悉T-SQL的这个功能。

1 个答案:

答案 0 :(得分:2)

T-SQL有一个很好的功能,在MySQL中没有直接的等价物。

ROW_NUMBER() OVER (PARTITION BY [year] ORDER BY MonthDate DESC) AS rn

然后rn = 1的任何东西都将成为一年中的最后一个条目。

这个问题的答案有一些想法:
ROW_NUMBER() in MySQL