Search code examples
t-sqldatetimesql-server-2008group-by

SQL Group by Year


This is my query.

SELECT CONVERT(varchar, cast(date as datetime), 3)
FROM shoptransfer 
GROUP BY year (date)

I want to group by the year part of the date (varchar) column, however I get the following error:

Column 'shoptransfer.Date' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

How do I group by the year part of the date column?


Solution

  • How about:

    select datepart(yyyy, [date]) as [year]
    from shoptransfer 
    group by datepart(yyyy, [date])
    

    Or:

    select count(*) as qty, datepart(yyyy, [date]) as [year]
    from shoptransfer 
    group by datepart(yyyy, [date])
    order by [year]
    

    This is based on OP's command: "I want to group by year part of date (varchar) column"