MSSQL Progressive accumulation function

Source: Internet
Author: User
Tags mssql

1. For example, build initial rainfall

2. In order to sort the rainfall, most of the operations can be omitted, with no subsequent rank being included

3. Observation, if we want to accumulate, in fact, the same day plus this day before the sum of rainfall, so you can write the following

Enclose the SQL code as follows:

SELECTRow_number () Over(ORDER  byTime) rank,*   into#t from(SELECT '2016-08-28'Time $RainfallUNION  All        SELECT '2016-08-29'Time0RainfallUNION  All        SELECT '2016-08-30'Time -RainfallUNION  All        SELECT '2016-08-31'Time theRainfallUNION  All        SELECT '2016-09-01'Time -RainfallUNION  All        SELECT '2016-09-02'Time0RainfallUNION  All        SELECT '2016-09-03'Time therainfall) aSELECTA1. Time, A1. Rainfall,sum(A2. Rainfall) Cumulative rainfall from#t A1INNER JOIN#t A2 onA2.rank<=A1.rankGROUP  byA1. Time, A1. RainfallORDER  byA1. TimeDROP TABLE#t

4. It is also possible to use the date as a condition without using row_number () and the effect is the same as 3:

Code:

SELECT *   into#t from(SELECT '2016-08-28'Time $RainfallUNION  All        SELECT '2016-08-29'Time0RainfallUNION  All        SELECT '2016-08-30'Time -RainfallUNION  All        SELECT '2016-08-31'Time theRainfallUNION  All        SELECT '2016-09-01'Time -RainfallUNION  All        SELECT '2016-09-02'Time0RainfallUNION  All        SELECT '2016-09-03'Time therainfall) aSELECTA1. Time, A1. Rainfall,sum(A2. Rainfall) Cumulative rainfall from#t A1INNER JOIN#t A2 onA2. Time<=A1. TimeGROUP  byA1. Time, A1. RainfallORDER  byA1. TimeDROP TABLE#t

Why 3 can find out what we want to look like, we just use the first three days to see

It can be observed that the record less than August 28 is August 28, less than August 29 is 28 and 292 days, we put these data together, we can easily A1 as the date of the group accumulation, and finally get the data we want.

MSSQL Progressive accumulation function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.