简体   繁体   中英

SQL Server : PRECEDING with another condition

I have a query that is working fine: The query is to find the sum & Avg for the last 3 months and last year. It is working fine, till I got a new request to break the query down to more details by AwardCode .

So how to include that?

I mean for this section

SUM(1.0 * InvolTerm) OVER (ORDER BY Calendar_Date ASC 
                           ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS  InvolMov3Mth,

I want to find the last 3 months based on AwardCode .

My original query that is working is

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

The result is

在此处输入图片说明

But now I need to add another group 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

The result will be like this

在此处输入图片说明

You can notice that the sum of InvolMov3Mth & TermSum12Mth for the whole period does not match the query above

I think I found the answer for my question.

I used PARTITION BY AwardCode before ORDER BY

seems to be working.

SUM(1.0*TotalTerm) OVER (PARTITION BY AwardCode ORDER BY Calendar_Date ASC 
                        ROWS BETWEEN 11 PRECEDING AND CURRENT ROW) AS TermSum12Mth,

Yes. "Partition by" will make it work for your requirment

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM