Skip to content
Advertisement

How to extract Year together with Month from this query

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

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement