简体   繁体   中英

How to Add one row to another

I have a set of data which is shown in picture:

数据集

I've tried adding January to February using the lead function which was correct shown in the picture below again:

使用 LEAD 后的结果

And I thought it will add and add to the next row like a for loop but it did not.

I am asking for help on how to add the data again and again like a for loop would do. I've pasted the code I used below.

;WITH MonthActiveUsers AS (

        SELECT MonthLogin, COUNT(MonthLogin) AS ActiveUsers
        FROM #TEMPDistinctActiveUsersPerMonth DAUPM
        GROUP BY MonthLogin     
)  
SELECT MAU.MonthLogin, (LEAD(MAU.ActiveUsers,0) OVER (ORDER BY MAU.MonthLogin ASC) + LEAD(MAU.ActiveUsers,1) OVER (ORDER BY MAU.MonthLogin ASC)) AS [Count of Active Users]
FROM 
    (   SELECT CASE 
                    WHEN MonthLogin = 'January'
                    THEN '2020-01-01'
                    WHEN MonthLogin = 'February'
                    THEN '2020-02-01'
                    WHEN MonthLogin = 'March'
                    THEN '2020-03-01'
                    WHEN MonthLogin = 'April'
                    THEN '2020-04-01'
                    WHEN MonthLogin = 'May'
                    THEN '2020-05-01'
                    WHEN MonthLogin = 'June'
                    THEN '2020-06-01'
                    ELSE NULL
                END AS [MonthLogin]
                ,ActiveUsers
        FROM MonthActiveUsers MAU
        ) MAU

The desired result would be:

January = 3313
February = 3349
March = 3398
April = 3421
May = 3437
June = 3444

I think that you want a window sum:

WITH ...
SELECT 
    MAU.MonthLogin, 
    SUM(MAU.ActiveUsers) OVER (ORDER BY MAU.MonthLogin) [Count of Active Users]
FROM ...

Note that the query can be simplified a little by using the short-circuit form of CASE , and mixing aggregation and window functions:

SELECT 
    MonthLogin,
    COUNT(*) ActiveUsers,
    SUM(COUNT(*)) OVER(ORDER BY MonthLogin) [Count of Active Users]
FROM (
    SELECT 
        CASE MonthLogin
            WHEN'January'   THEN '2020-01-01'
            WHEN'February'  THEN '2020-02-01'
            WHEN'March'     THEN '2020-03-01'
            WHEN'April'     THEN '2020-04-01'
            WHEN'May'       THEN '2020-05-01'
            WHEN'June'      THEN '2020-06-01'
        END AS MonthLogin
    FROM #TEMPDistinctActiveUsersPerMonth
) t
GROUP BY MonthLogin
ORDER BY MonthLogin

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