Calculate the sum for each month

ooj-4672 60 Reputation points
2023-06-22T07:04:26.9266667+00:00

Hello.

I have the following table.

Date               Value

20230302      8

20230316      10

20230325      3

20230410      6

20230415      6

20230426      2


Expect results:

User's image


Can someone help me?

SQL Server Other
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2023-06-22T07:09:11.25+00:00

    Hi @sleep

    You can try this query.

    create table test(Date datetime,Value int);
    insert into test values
    ('20230302',8),
    ('20230316',10),
    ('20230325',3),
    ('20230410',6),
    ('20230415',6),
    ('20230426',2);
    
    ;with CTE as(
      select eomonth(Date) as Date,sum(Value) as sum from test group by eomonth(Date))
    select year(Date) as year,month(Date) as month,sum from CTE;
    

    Output:

    User's image

    Best regards,

    Percy Tang


    If the answer is the right solution, please click "Accept Answer". 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.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

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.