我有一个运行良好的查询:该查询用于查找最近3个月和去年的总和和平均值。一切正常,直到我收到一个新请求,以AwardCode
将查询细分为更多详细信息。
那怎么包括呢?
我的意思是本节
SUM(1.0 * InvolTerm) OVER (ORDER BY Calendar_Date ASC
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS InvolMov3Mth,
我想根据AwardCode
查找最近3个月。
正在运行的原始查询是
SELECT
Calendar_Date, Mth, NoOfEmp, MaleCount, FemaleCount,
SUM(1.0*InvolTerm) OVER (ORDER BY Calendar_Date ASC
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS InvolMov3Mth,
SUM(1.0*TotalTerm) OVER (ORDER BY Calendar_Date ASC
ROWS BETWEEN 11 PRECEDING AND CURRENT ROW) AS TermSum12Mth
FROM @X
结果是
但是现在我需要添加另一个组AwardCode
SELECT
Mth, AwardCode, NoOfEmp, MaleCount, FemaleCount,
SUM(1.0 * InvolTerm) OVER (ORDER BY Calendar_Date ASC
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS InvolMov3Mth,
SUM(1.0 * TotalTerm) OVER (ORDER BY Calendar_Date ASC
ROWS BETWEEN 11 PRECEDING AND CURRENT ROW) AS TermSum12Mth
FROM @X
结果将是这样
您会注意到整个期间的InvolMov3Mth和TermSum12Mth的总和与上面的查询不匹配
答案 0 :(得分:1)
我想我找到了问题的答案。
我在ORDER BY之前使用了PARTITION BY AwardCode
似乎正在工作。
SUM(1.0*TotalTerm) OVER (PARTITION BY AwardCode ORDER BY Calendar_Date ASC
ROWS BETWEEN 11 PRECEDING AND CURRENT ROW) AS TermSum12Mth,
答案 1 :(得分:1)
是的。 “分区依据”将使其适合您的要求