0

I have a query to show total orders by month based on a date column. May I know how to append year to the Month column?

select DATENAME(MONTH,DATEADD(MONTH, MONTH(<column>) - 1, 0)) AS Month,
    count(*) AS Total_Request
from <table>
group by month(<column>)

enter image description here

Dale K
  • 25,246
  • 15
  • 42
  • 71
JL_Coder
  • 152
  • 1
  • 4
  • 12

2 Answers2

3

From SQL Server 2012 you can use FORMAT function

SELECT 
     FORMAT( YourColumn, 'yyyy-MMMM')
     ,COUNT(*) AS Total_Request
FROM 
    <table>
GROUP BY 
    FORMAT( YourColumn, 'yyyy-MMMM')
        

You can also add a culture as third parameter. Below the syntax SQL:

FORMAT ( value, format [, culture ] )

For documentation look here

Gabriele Franco
  • 879
  • 6
  • 10
2

I would just aggregate directly by the year and month, as a single text field:

SELECT
    CONVERT(varchar(7), <column>, 120) AS Year-Month,
    COUNT(*) AS Total_Request
FROM <table>
GROUP BY
    CONVERT(varchar(7), <column>, 120);

If you really want the year and three letter abbreviation for the month, you may try:

SELECT
    YEAR(<column>) AS Year,
    LEFT(DATENAME(MONTH, <column>), 3) AS Month,
    COUNT(*) AS Total_Request
FROM <table>
GROUP BY
    YEAR(<column>),
    LEFT(DATENAME(MONTH, <column>), 3);
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360