Home > Software design >  How to query months and group them in SQL Server
How to query months and group them in SQL Server

Time:06-12

I have a query which sums up the transactions of a given month over a given period in SQL Server. I want to list the months and transactions in a table but the DATENAME() function is only returning one month i.e January in the list. The query is as shown below ..

SELECT 
    DATENAME(MONTH, DATEPART(MONTH FROM TransactionDate)) AS Month_Name, 
    SUM(ABS(Income)) AS Income 
FROM 
    Transactions 
GROUP BY 
    DATEPART(MONTH FROM TransactionDate)

Please help ...

CodePudding user response:

Try this,

SELECT 
  datename(mm,TransactionDate) AS Month_Name, 
  SUM(ABS(Income)) AS Income 
FROM Transactions 
GROUP BY 
  datename(mm, TransactionDate)

CodePudding user response:

Try this:

select datename(mm, TransactionDate) month_name, sum(income) income
from transactions
group by month_name

Remove some unnecessary to tune up the performance.

  • Related