ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW on sum column

stasv85 1 Reputation point
2022-02-10T18:29:18.2+00:00

how can i add
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW on sum column? because the lead/lag function dont work

used the cod :

select year (orderdate),month (orderdate),sum (SubTotal),
lead ( sum (SubTotal),0) OVER ( PARTITION BY sum (SubTotal) ORDER BY sum (SubTotal) ) as PrevOrder
from sales.SalesOrderHeader
where orderdate <= '2011-12-31'173283-sub-my-code.jpg173226-expected.jpg
group by 173207-sub1.jpg
grouping sets
((year (orderdate),month (orderdate)), () )

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
14,014 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,657 questions
{count} votes

2 answers

Sort by: Most helpful
  1. LiHong-MSFT 10,051 Reputation points
    2022-02-11T02:23:02.12+00:00

    Hi @stasv85

    because the lead/lag function dont work

    The reason is that you set lead offset = 0.
    Basic Syntax :

    LAG (scalar_expression [,offset] [,default]) OVER ( [ partition_by_clause ] order_by_clause )

    Have a change like this : lag ( sum (salary),1,0) OVER ( ORDER BY sum (salary)) as PrevOrder
    For more details about LAG , please refer to this document: LAG (Transact-SQL)

    Best regards,
    LiHong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  2. LiHong-MSFT 10,051 Reputation points
    2022-02-11T03:03:02.503+00:00

    Hi @stasv85

    how can i add ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW on sum column?

    Try this:

    select year (orderdate) [Year],month (orderdate) [Month],sum (SubTotal) [Sum_price],   
           sum (sum (SubTotal))over(partition by year (orderdate) order by year (orderdate),month (orderdate)  ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW )[Money]   
    from sales.SalesOrderHeader   
    where orderdate <= '2011-12-31'   
    group by grouping sets   
    ((year (orderdate),month (orderdate)))   
    

    If it is not working or helpful, please provide more sample data (CREATE TABLE …)(INSERT INTO …) or details about your issue.
    Please refer to this article for some examples:https://learnsql.com/blog/sql-window-functions-rows-clause/
    Best regards,
    LiHong

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.